首页 > 其他 > 详细

[leetcode]Intersection of Two Linked Lists

时间:2015-01-01 00:08:59      阅读:282      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!