首页 > 其他 > 详细

leetcode - Intersection of Two Linked Lists

时间:2015-06-09 16:35:02      阅读:226      评论:0      收藏:0      [点我收藏+]

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

leetcode - Intersection of Two Linked Lists

原文:http://www.cnblogs.com/shnj/p/4563448.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!