leetcode - Intersection of Two Linked Lists

leetcode - 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.
 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 == NULL || headB == NULL){
13             return NULL;
14         }
15         ListNode *tpA = headA;
16         ListNode *tpB = headB;
17         int numA=0,numB=0;
18         while(tpA != NULL){
19             tpA = tpA->next;
20             numA++;
21         }
22         while(tpB != NULL){
23             tpB = tpB->next;
24             numB++;
25         }
26         tpA = headA;
27         tpB = headB;
28         if(numA!=numB){
29             if(numA>numB){
30                 for( int i = 0; i<(numA-numB); i++){
31                     tpA = tpA->next;
32                 }
33             }
34             else{
35                 for( int i = 0; i<(numB-numA); i++){
36                     tpB = tpB->next;
37                 }
38             }
39         }
40         while(tpA != NULL){
41             if(tpA == tpB){
42                 return tpA;
43             }
44             else{
45                 tpA = tpA->next;
46                 tpB = tpB->next;
47             }
48         }
49         return NULL;
50     }
51 };

 头一次一遍就AC……

个人思路:先计数,然后把起始点定好,都定在距离最后一个节点一样距离的地方。然后同步前进遍历即可。

 

改进:

为了节省计算,在计算链表长度的时候,顺便比较一下两个链表的尾节点是否一样,

若不一样,则不可能相交,直接可以返回NULL

posted @ 2015-06-09 14:18  cnblogshnj  阅读(165)  评论(0编辑  收藏  举报