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

Leetcode 160. 相交链表

时间:2018-08-12 14:21:17      阅读:112      评论:0      收藏:0      [点我收藏+]

标签:val   style   etc   tno   struct   cti   lis   ==   next   

/**
 * 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 cnt = 0;
        ListNode * tmp =  headA;
        while(tmp)
        {
            cnt++;
            tmp = tmp->next;
        }
        tmp = headB;
        while(tmp)
        {
            cnt--;
            tmp = tmp->next;
        }
        
        ListNode* another = NULL;
        tmp = cnt>0 ?headA:headB;
        another = tmp==headA?headB:headA;
        cnt = cnt>0?cnt:-1*cnt;
        while(cnt)
        {
            tmp=tmp->next;
            cnt--;
        }
        
        while(tmp && another)
        {
            if(tmp == another)
            {
                return tmp;
            }
            tmp=tmp->next;
            another= another->next;
        }
        return NULL;
    }
};

 

Leetcode 160. 相交链表

标签:val   style   etc   tno   struct   cti   lis   ==   next   

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

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