码迷,mamicode.com
首页 > 其他好文 > 详细

Intersection of Two Linked Lists

时间:2015-08-30 12:49:27      阅读:134      评论:0      收藏:0      [点我收藏+]

标签:

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.

 

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        int Alength = 0;
        int Blength = 0;
        ListNode* ptra = headA;
        ListNode* ptrb = headB;
        
        while(ptra){
            ptra = ptra->next;
            Alength++;
        }
        while(ptrb){
            ptrb = ptrb->next;
            Blength++;
        }
        
        int x = Alength - Blength;
        if(x < 0){
            ptrb = headB;
            ptra = headA;
            for(int i = 0; i < -x; i++){
                ptrb = ptrb->next;
            }
        }
        else{
            ptra = headA;
            ptrb = headB;
            for(int i = 0; i < x; i++){
                ptra = ptra->next;
            }
        }
        
        while(ptra){
            if(ptra == ptrb)
                return ptra;
            ptra = ptra->next;
            ptrb = ptrb->next;
        }
        return ptra;
    }
};

 

Intersection of Two Linked Lists

标签:

原文地址:http://www.cnblogs.com/horizonice/p/4770514.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!