面试题52.两个链表的第一个公共节点
题目
编写一个程序,找到两个单链表相交的起始节点。
如下面的两个链表:
在节点 c1 开始相交。
P.S.题目来源于leetcode
解题思路
解法1:hash map
使用一个集合存储A的所有节点,再判断B的节点是否再lookUp中,若在则说明是相交的节点,否则查询完毕不存在相交点
code1:hash map
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
#简单思路:哈希表法
lookUp = set()#存储A的所有节点
#先存储A所有节点
curA = headA
while curA:
lookUp.add(curA)
curA = curA.next
#再判断B的节点是否再lookUp中,若在则说明是相交的节点
cur_B = headB
while cur_B:
if cur_B in lookUp: return cur_B
cur_B = cur_B.next
else: return None#查询完不存在相交点
解法2:双指针
第一次遍历找到长度差,第二次长链先走长度差,再找交叉节点
code2: bi-pointer
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
#简单思路:双指针(两次遍历),第一次遍历找到长度差,第二次长链先走长度差,再找交叉节点
#first: find the length difference
curA,curB = headA,headB
numA = numB = 0
while curA:
numA += 1
curA = curA.next
while curB:
numB += 1
curB = curB.next
diff = abs(numA-numB)
#second: let the long chain go `diff` first, then to get the intersection.
curA,curB = headA,headB
if numA<numB:#let long chain go `diff` steps first
for i in range(diff):
curB = curB.next
else:
for i in range(diff):
curA = curA.next
while curA:#get the intersection
if curA == curB: return curA
curA = curA.next
curB = curB.next
return None