国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計 > 正文

Leetcode 160. Intersection of Two Linked Lists

2019-11-11 05:03:14
字體:
供稿:網(wǎng)友

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.

s思路: 1. 這道題確實(shí)做過,印象深刻。通過做輔助線,把問題轉(zhuǎn)換成熟悉的問題,再用熟悉的配方來解決。假設(shè)有兩條鏈表A,B,我們先遍歷A到A的結(jié)尾然后把A的尾巴指向A的頭部,這樣一來,就有一個cycle,如果我們再從B開始用快慢指針大法去檢測這個cycle,并找到cycle所在的地方,就是兩條鏈表的intersection 開始的地方。如果AB沒有intersection,那么我們遍歷B就不會遇到cycle。 這里寫圖片描述

class Solution {public: ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { if(!headA||!headB) return NULL; ListNode* pa=headA,*pb=headB; //step 1:A首尾相連成閉環(huán) while(pa&&pa->next){ pa=pa->next; } pa->next=headA; //step 2:快慢指針檢測是否cycle ListNode* fast=headB->next,*slow=headB; while(fast&&fast!=slow){ fast=fast->next?fast->next->next:NULL; slow=slow->next; } if(fast) { fast=headB; slow=slow->next; //step 3: 定位cycle起始 while(fast!=slow){ fast=fast->next; slow=slow->next; } } //step4: 斷開剛才引入的cycle pa->next=NULL; return fast; }};
發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 兴山县| 金川县| 扶余县| 长岭县| 丁青县| 舞钢市| 宿迁市| 余姚市| 嘉兴市| 新干县| 确山县| 南和县| 北流市| 宁蒗| 钟山县| 岐山县| 富平县| 牙克石市| 莒南县| 涞水县| 新昌县| 长沙县| 文山县| 安新县| 天峨县| 民权县| 依安县| 辽宁省| 木里| 砚山县| 平泉县| 云霄县| 高台县| 太仓市| 北海市| 宁陵县| 台湾省| 通城县| 郧西县| 长丰县| 天等县|