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

LeetCode 160. Intersection of Two Linked Lists

时间:2018-07-14 10:20:12      阅读:195      评论:0      收藏:0      [点我收藏+]

标签:ext   solution   ++   str   code   ==   amp   null   return   

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    int getLen(ListNode* head)
    {
        int len = 0;
        while(head)
        {
            ++len;
            head = head->next;
        }
        return len;
    }
    
    ListNode *forward_long_list(int long_len, int short_len, ListNode *head)
    {
        int delta = long_len - short_len;
        while(head && delta)
        {
            head = head->next;
            --delta;
        }
        return head;
    }
    
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        int lenA = getLen(headA);
        int lenB = getLen(headB);
        if(lenA > lenB) headA = forward_long_list(lenA, lenB, headA);
        else headB = forward_long_list(lenB, lenA, headB);
        
        while(headA && headB)
        {
            if(headA == headB)
                return headA;
            headA = headA->next;
            headB = headB->next;
        }
        return NULL;
    }
};

 

LeetCode 160. Intersection of Two Linked Lists

标签:ext   solution   ++   str   code   ==   amp   null   return   

原文地址:https://www.cnblogs.com/randyniu/p/9308566.html

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