[勇者闯LeetCode] 160. Intersection of Two Linked Lists

来源:互联网 发布:德国公开赛 知乎 编辑:程序博客网 时间:2024/06/05 19:07

[勇者闯LeetCode] 160. Intersection of Two Linked Lists

Description

Write a program to find the node at which the intersection of two singly linked lists begins.
For example, the following two linked list

A:          a1 → a2                   ↘                     c1 → c2 → c3                   ↗            B:     b1 → b2 → b3

Notes:
If the two linked lists have no intersection at all, return null.
The linked lists must retain their original structure after the function returns.
You may assume there are no cycles anywhere in the entire linked structure.
Your code should preferably run in O(n) time and use only O(1) memory.

Information

  • Tags: Linked List
  • Difficulty: Easy

Solution

两个指针分别从两个链表的头部开始扫描,到达尾部后跳到另一个链表的头部继续扫描,则扫描过程中两个指针相遇的点即为两个链表开始相交的点。

Python Code

# Definition for singly-linked list.# class ListNode(object):#     def __init__(self, x):#         self.val = x#         self.next = Noneclass Solution(object):    def getIntersectionNode(self, headA, headB):        """        :type head1, head1: ListNode        :rtype: ListNode        """        currA, currB = headA,headB        begin, tailA, tailB = None, None, None        while currA and currB:            if currA == currB:                begin = currA                break            if currA.next:                currA = currA.next            elif tailA is None:                tailA = currA                currA = headB            else:                break            if currB.next:                currB = currB.next            elif tailB is None:                tailB = currB                currB = headA            else:                break        return begin
原创粉丝点击