Leetcode 160.相交链表
1 题目描述(Leetcode题目链接)
编写一个程序,找到两个单链表相交的起始节点。如下面的两个链表:
在节点 c1 开始相交。
输入:intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3
输出:Reference of the node with value = 8
输入解释:相交节点的值为 8 (注意,如果两个列表相交则不能为 0)。从各自的表头开始算起,链表 A 为 [4,1,8,4,5],链表 B 为 [5,0,1,8,4,5]。在 A 中,相交节点前有 2 个节点;在 B 中,相交节点前有 3 个节点。
2 题解
算长度,然后再同一个起点开始走。
# 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:
lenA = 0
lenB = 0
pa, pb = headA, headB
while pa:
lenA += 1
pa = pa.next
while pb:
lenB += 1
pb = pb.next
pa, pb = headA, headB
if lenA < lenB:
lenA, lenB = lenB, lenA
pa, pb = pb, pa
while lenA > lenB:
pa = pa.next
lenA -= 1
while lenA:
if pa == pb:
return pa
pa = pa.next
pb = pb.next
return None
还有更巧妙的方法,就是两个指针一起走,一定会有一个指针先到链表尾部,那么这时候就让这个指针指向另一个链表头,这时候两个指针就是并排行走了。
# 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:
pa, pb = headA, headB
while pa != pb:
if not pa:
pa = headB
else:
pa = pa.next
if not pb:
pb = headA
else:
pb = pb.next
return pa