160. Intersection of Two Linked Lists
創(chuàng)新互聯(lián)成立10余年來(lái),這條路我們正越走越好,積累了技術(shù)與客戶資源,形成了良好的口碑。為客戶提供成都網(wǎng)站建設(shè)、成都做網(wǎng)站、網(wǎng)站策劃、網(wǎng)頁(yè)設(shè)計(jì)、域名注冊(cè)、網(wǎng)絡(luò)營(yíng)銷(xiāo)、VI設(shè)計(jì)、網(wǎng)站改版、漏洞修補(bǔ)等服務(wù)。網(wǎng)站是否美觀、功能強(qiáng)大、用戶體驗(yàn)好、性價(jià)比高、打開(kāi)快等等,這些對(duì)于網(wǎng)站建設(shè)都非常重要,創(chuàng)新互聯(lián)通過(guò)對(duì)建站技術(shù)性的掌握、對(duì)創(chuàng)意設(shè)計(jì)的研究為客戶提供一站式互聯(lián)網(wǎng)解決方案,攜手廣大客戶,共同發(fā)展進(jìn)步。
Write a program to find the node at which the intersection of two singly linked lists begins.
For example, the following two linked lists:
A: a1 → a2 ↘ c1 → c2 → c3 ↗ B: b1 → b2 → b3
begin to intersect at node c1.
Notes:
If the two linked lists have no intersection at all, return null
.
The linked lists must retain their original structure after the function returns.
You may assume there are no cycles anywhere in the entire linked structure.
Your code should preferably run in O(n) time and use only O(1) memory.
題目大意:
找出兩個(gè)鏈表后半部分的交匯點(diǎn)。
思路:
1.求出兩個(gè)鏈表的長(zhǎng)度。
2.獲取鏈表長(zhǎng)度差n。
3.將長(zhǎng)的鏈表先移動(dòng)到第n個(gè)節(jié)點(diǎn)。
4.對(duì)長(zhǎng)鏈表和短鏈表進(jìn)行比較。(同時(shí)向后移動(dòng))如果在鏈表尾之前找到相等的節(jié)點(diǎn),返回該節(jié)點(diǎn),如果沒(méi)找到,返回NULL。
代碼如下:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: int listLength(ListNode *head)//用快指針求鏈表長(zhǎng)度 { ListNode * p = head; int i = 0 ; while(p && p->next) { i++; p = p->next->next; } if(p == NULL) return 2 * i; return 2 * i + 1; } ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { int lenA = listLength(headA); int lenB = listLength(headB); int maxLen = lenA > lenB ? lenA :lenB; int remain ; ListNode * la,*lb; la = headA; lb = headB; if(maxLen == lenA) { remain = lenA - lenB; while(remain--) { la = la->next; } } else { remain = lenB - lenA; while(remain--) lb = lb->next; } while(lb != NULL) { if(la != lb) { la = la->next; lb = lb->next; } else { return la; } } return NULL; } };
2016-08-13 01:08:14