剑指Offer34:两个链表的第一个公共结点

思路:

先将head1的所有结点值放到一个列表list1中,然后判断head2中的结点是否在list1中,若在则返回,反之则继续判断。

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
  
class Solution:
    def FindFirstCommonNode(self, head1, head2):
        # write code here
        list1 = []
        list2 = []
        node1 = head1
        node2 = head2
        while node1:
            list1.append(node1.val)
            node1 = node1.next
        while node2:
            if node2.val in list1:
                return node2
            else:
                node2 = node2.next

有个思路,不需要存储链表的额外空间。也不需要提前知道链表的长度。看下面的链表例子:

0-1-2-3-4-5-null

a-b-4-5-null

如果有公共结点,那么指针一起走到末尾的部分,也就一定会重叠。看看下面指针的路径吧。

p1: 0-1-2-3-4-5-null(此时遇到ifelse)-a-b-4-5-null

p2:  a-b-4-5-null(此时遇到ifelse)0-1-2-3-4-5-null

class Solution:
    def FindFirstCommonNode(self, pHead1, pHead2):
        p1,p2=pHead1,pHead2
        while p1!=p2:
            if p1!=None:
                 p1 = p1.next
            else:
                 p1 = pHead2
            p2 = p2.next if p2 else pHead1
        return p1

学习大佬的思想。。。

猜你喜欢

转载自blog.csdn.net/weixin_43160613/article/details/85156988