1. 程式人生 > >Leetcode 160. 相交鏈表

Leetcode 160. 相交鏈表

ini adb fin {} cti nod val node tint

/**
 * 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. 相交鏈表