LeetCode 160. Intersection of Two Linked Lists

Write a program to find the node at which the intersection of two singly linked lists begins.

 

For example, the following two linked lists:

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

begin to intersect at node c1.

 

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.

 

Credits:
Special thanks to @stellari for adding this problem and creating all test cases.

 

这道题是说寻找两个链表的公共部分的起始节点,有这么几个方法:

1、暴力搜索

时间复杂度太高

2、使用hash表

空间复杂度不满足要求

3、双指针

方法非常巧妙,设置两个指针分别从两个链表头部开始遍历,如果某个指针到达尾部,则从另一个链表头部开始,最后两个指针相遇的地方就是公共节点

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
12         if (!headA || !headB)
13             return nullptr;
14         ListNode *a = headA, *b = headB;
15         while (a != b)
16         {
17             a = a ? a->next : headB;
18             b = b ? b->next : headA;
19         }
20         return a;
21     }
22 };

 

时间复杂度:O(m+n)

空间复杂度:O(1)

 

参考:https://leetcode.com/problems/intersection-of-two-linked-lists/solution/

https://leetcode.com/problems/intersection-of-two-linked-lists/discuss/49799

 

posted @ 2018-01-12 16:16  皇家大鹏鹏  阅读(151)  评论(0编辑  收藏  举报