-
- 相交链表:编写一个程序,找到两个单链表相交的起始节点。
- 思路:表1的长度是x1+y,链表2的长度是x2+y,我们同时遍历链表1和链表2,到达末尾时,再指向另一个链表。则当两链表走到相等的位置时:
x1+y+x2 = x2+y+x1
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
a = headA
b = headB
while a!=b:
a = a.next if a else headB
b = b.next if b else headA
return a