/** * 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; } };
原文地址:https://www.cnblogs.com/randyniu/p/9462411.html
时间: 2024-11-02 02:54:56