题目描述
输入两个链表,找出它们的第一个公共结点。
解法1
使用栈,将两个链表的node保存在栈中,因为如果有公共节点说明next相同,则后面的节点都是相同的
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def FindFirstCommonNode(self, pHead1, pHead2):
# write code here
stack1, stack2 = [], []
if pHead1 == None or pHead2 == None:
return None
while pHead1:
stack1.append(pHead1)
pHead1 = pHead1.next
while pHead2:
stack2.append(pHead2)
pHead2 = pHead2.next
print(stack1, stack2)
while True:
pop1 = stack1.pop()
pop2 = stack2.pop()
print(pop1, pop2)
if pop1 != pop2:
return None
if stack1 == [] or stack2 == [] or stack1[len(stack1) - 1] != stack2[len(stack2) - 1]:
return pop1
运行时间:32ms
占用内存:5752k
解法2
首先算出两个链表的长度,算出长度差值之后,长的链表先向后遍历这个差值,然后同步遍历。第一个相同的node就是解
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def FindFirstCommonNode(self, pHead1, pHead2):
if pHead1 == None or pHead2 == None:
return None
length1, length2 = 0, 0
pNode1, pNode2 = pHead1, pHead2
while pNode1:
length1 += 1
pNode1 = pNode1.next
while pNode2:
length2 += 1
pNode2 = pNode2.next
if length2 >= length1:
differLength = length2 - length1
while differLength:
pHead2 = pHead2.next
differLength -= 1
else:
differLength = length1 - length2
while differLength:
pHead1 = pHead1.next
differLength -= 1
while pHead1 != pHead2:
pHead1 = pHead1.next
pHead2 = pHead2.next
return pHead1
运行时间:27ms
占用内存:5724k