LeetCode(160) Intersection of Two Linked Lists

来源:互联网 发布:淘宝批量发货收费吗 编辑:程序博客网 时间:2024/05/13 20:03

题目如下:

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.


分析如下:

这道题目其实和之前的一道题目 Linked List Cycle II 一样,只需要把这道题目中的一条list的尾巴连接到另一条list的头部,就变成了Linked List Cycle II这道题目了。


我的代码:

[cpp] view plaincopyprint?
  1. //288ms   
  2. class Solution {  
  3. public:  
  4.     ListNode *detectCycle(ListNode *head) {  
  5.         ListNode* fast = head;  
  6.         ListNode* slow = head;  
  7.         while (slow != NULL && fast != NULL) {  
  8.             slow = slow->next;  
  9.             fast = fast->next;  
  10.             if(fast != NULL)  
  11.                 fast = fast->next;  
  12.             if (fast == slow)  
  13.                 break;  
  14.         }  
  15.         if (fast == NULL) return NULL;  
  16.         slow = head;  
  17.         while (slow != fast) {  
  18.             slow = slow->next;  
  19.             fast = fast->next;  
  20.         }  
  21.         return fast;  
  22.     }  
  23.       
  24.     ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {  
  25.         ListNode* keepHeadB = headB;  
  26.         ListNode* keepTailB = headB;  
  27.         if (headA == NULL || headB == NULL) return NULL;  
  28.         while (headB->next != NULL)   
  29.             headB = headB->next;  
  30.         keepTailB = headB;      
  31.         headB->next = headA;  
  32.         ListNode* cycleBegin = detectCycle(keepHeadB);  
  33.         keepTailB->next = NULL;  
  34.         return cycleBegin;  
  35.     }  
  36. };  
0 0
原创粉丝点击