ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

【剑指offer】37. 两个链表的第一个公共节点(python)

2019-02-24 12:49:37  阅读:240  来源: 互联网

标签:offer python self next 链表 while pHead1 pHead2


题目描述

输入两个链表,找出它们的第一个公共结点。

思路

《剑指offer》P193

  • 方法一
    使用辅助空间栈,遍历两个链表,将节点保存到栈中。然后利用栈先进后出的特点找到公共节点。
  • 方法二
    先遍历一遍得到两个链表的长度mn,假设m>n,则较长的链表先走m-n步,然后两个链表同时向后走,直到找到第一个公共节点。

code

  • 方法一
# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    def FindFirstCommonNode(self, pHead1, pHead2):
        # write code here
        while not pHead1 or not pHead2:
            return None
        # 遍历两个链表,将节点保存到栈中
        # 然后利用栈先进后出的特点找到公共节点
        stack1 = []
        stack2 = []
        while pHead1:
            stack1.append(pHead1)
            pHead1 = pHead1.next
        while pHead2:
            stack2.append(pHead2)
            pHead2 = pHead2.next
        commonNode = None
        while stack2 and stack1:
            node1 = stack1.pop()
            node2 = stack2.pop()
            if node1 != node2:
                break
            else:
                commonNode = node1
        return commonNode
  • 方法二
# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    def FindFirstCommonNode(self, pHead1, pHead2):
        # write code here
        while not pHead1 or not pHead2:
            return None
        len1 = 0
        len2 = 0
        pNode1 = pHead1
        pNode2 = pHead2
        # 先计算长度
        while pNode1:
            len1 += 1
            pNode1 = pNode1.next
        while pNode2:
            len2 += 1
            pNode2 = pNode2.next
        # 较长的链表先移动
        while len1 > len2:
            pHead1 = pHead1.next
            len1 -= 1
        while len2 > len1:
            pHead2 = pHead2.next
            len2 -= 1
        # 两个链表同时移动
        while pHead2 and pHead1:
            if pHead2 == pHead1:
                break
            else:
                pHead2 = pHead2.next
                pHead1 = pHead1.next
        return pHead2

标签:offer,python,self,next,链表,while,pHead1,pHead2
来源: https://blog.csdn.net/u014568072/article/details/87901982

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有