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

[leetcode]Intersection of Two Linked Lists

时间:2014-11-28 00:58:38      阅读:258      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   sp   for   on   div   log   

又是个老提

先判断是否相交,如果相交,那么两个链表最后的节点是一样的。

相交那么,我们就来找相交的那个点,假设两个链表一样长,一起往后走,到相同的那个就是交点,不一样长,我们把长的切掉,然后继续这样找就好了。

 

/**
 * 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) {
        if (headA == nullptr || headB == nullptr) return nullptr;
        int la = 0;
        int lb = 0;
        ListNode* tmpA = headA;
        ListNode* tmpB = headB;
        while(tmpA -> next != nullptr) {
            la++;
            tmpA = tmpA -> next;
        }
        while(tmpB -> next != nullptr) {
            lb++;
            tmpB = tmpB -> next;
        }
        if (tmpA != tmpB) return nullptr;
        tmpA = headA;
        tmpB = headB;
    
        if (lb < la) {
        // la must less than lb
            swap(tmpA, tmpB);
            swap(la, lb);
        }
        int diff = lb - la;
        for (int i = 0; i < diff; i++) {
            tmpB = tmpB -> next;
        }
    
        while (tmpA != tmpB) {
            tmpA = tmpA -> next;
            tmpB = tmpB -> next;
        }
        return tmpA;
    }
};

 

[leetcode]Intersection of Two Linked Lists

标签:style   blog   io   color   sp   for   on   div   log   

原文地址:http://www.cnblogs.com/x1957/p/4127492.html

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