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

[leetcode]Intersection of Two Linked Lists

时间:2015-01-01 00:09:21      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:

老题了。

class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        ListNode *tailA = headA;
        ListNode *tailB = headB;
        int lengthA = getLength(headA, tailA);
        int lengthB = getLength(headB, tailB);
        if (tailA != tailB || tailA == NULL) {
            return NULL;
        }
        ListNode *nodeA = headA;
        ListNode *nodeB = headB;
        int diff = abs(lengthA - lengthB);
        while (diff--) {
            if (lengthA > lengthB) {
                nodeA = nodeA->next;    
            } else {
                nodeB = nodeB->next;
            }
        }
        while (nodeA != nodeB) {
            nodeA = nodeA->next;
            nodeB = nodeB->next;
        }
        return nodeA;
    }
    
    int getLength(ListNode *head, ListNode *&tail) {
        if (head == NULL) {
            tail = NULL;
            return 0;
        }
        int length = 1;
        ListNode *node = head;
        while (node->next != NULL) {
            node = node->next;
            length++;
        }
        tail = node;
        return length;
    }
};

  

[leetcode]Intersection of Two Linked Lists

标签:

原文地址:http://www.cnblogs.com/lautsie/p/4196785.html

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