找出链表的交点, 如图所示的c1, 如果没有相交返回null.
A: a1 → a2
↘
c1 → c2 → c3
↗
B: b1 → b2 → b3
我的方法是:
(1)统计两个链表的长度
(2)移动较长的链表的表头,使得让两个链表的长度一致
(3)从修正后的表头出发对比两个链表的节点是否一致,输出一致的节点,否则输出null
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 int list_len(ListNode* head){ 12 int cnt = 0; 13 for(ListNode* now = head; now; now = now->next){ 14 ++cnt; 15 } 16 return cnt; 17 } 18 ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { 19 int al = list_len(headA); 20 int bl = list_len(headB);//(1) 21 ListNode* minh = headA; 22 ListNode* maxh = headB; 23 int cnt = bl - al; 24 if(al > bl) { 25 maxh = headA; 26 minh = headB; 27 cnt = -cnt; 28 } 29 while(cnt--){ 30 maxh = maxh->next; 31 } //(2) 32 for( ;maxh && minh ; maxh = maxh->next, minh = minh->next){ 33 if(maxh == minh) return maxh; 34 } 35 return NULL; //(3) 36 } 37 };