题目描述
输入两个链表,找出它们的第一个公共结点。
首先弄明白,两个链表的公共节点是什么。是pHead1和pHead2在某个节点都指向了同一个节点。
方法1.
#用栈的方法(剑指offer书上的方法)
#构建两个栈,相当于将链表的顺序反过来,这样,两个链表最后一个不相同的节点,就是第一个公共节点。
class Solution:
def FindFirstCommonNode(self, pHead1, pHead2):
# write code here
if not pHead1 or not pHead2:
return
stack1 = []
stack2 = []
while pHead1 != None:
stack1.append(pHead1)
pHead1 = pHead1.next
while pHead2 != None:
stack2.append(pHead2)
pHead2 = pHead2.next
first = None
while stack1 and stack2:
top1 = stack1.pop()
top2 = stack2.pop()
if top1 is top2:
first = top1
else:
break
return first
方法2.
方法1利用栈主要解决就是同时到达第一个结点的问题。
从链表头出发如何同时到达第一个相同的结点.
链表的长度相同就可以,其实就是走的结点数目相同。所以可以让其中长的链表先走几步,剩余的长度到短链表的长度相同。
#将长度长的链表的前面部分删除
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def FindFirstCommonNode(self, head1, head2):
if not head1 or not head2:
return None
p1, p2= head1, head2
length1 = length2 = 0
while p1:
length1 += 1
p1 = p1.next
while p2:
length2 += 1
p2 = p2.next
if length1 > length2:
while length1 - length2:
head1 = head1.next
length1 -= 1
else:
while length2 - length1:
head2 = head2.next
length2 -= 1
while head1 and head2:
if head1 is head2:
return head1
head1 = head1.next
head2 = head2.next
return None