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

首頁 > 學院 > 開發設計 > 正文

鏈表中環的入口節點

2019-11-08 03:07:17
字體:
來源:轉載
供稿:網友

題目描述

一個鏈表中包含環,請找出該鏈表的環的入口結點。

算法描述: 受之前的面試題的啟發,如果我們在一個有環的鏈表中設置兩個鏈表指針,一個快,一個慢,那么兩個鏈表指針相遇的時候,必然是位于鏈表中的某個結點,利用這個結點,當我們從這個結點開始繼續遍歷,當再一次回到這個結點的時候,我們可以統計出環中的結點數,這個時候將兩個指針重置到鏈表頭,讓其中一個結點先走夠環的結點數,然后兩個指針同時走,當兩個結點相遇的時候,這個結點就是入口結點。

代碼如下:

public ListNode meetingNode(ListNode pHead){ if (pHead == null){ return null; } ListNode slow = pHead.next; if (slow == null){ return null; } ListNode fast = slow.next; while (slow != null && fast != null){ if (slow == fast){ return slow; } slow = slow.next; fast = fast.next; if (fast != null){ fast = fast.next; } } return null; } public ListNode EntryNodeOfLoop(ListNode pHead) { ListNode meetingNode = meetingNode(pHead); if (meetingNode == null){ return null; } int countInLoop = 1; ListNode pNode = meetingNode; while (pNode.next != meetingNode){ pNode = pNode.next; ++ countInLoop; } pNode = pHead; for (int i = 0; i < countInLoop; i++) { pNode = pNode.next; } ListNode PResult = pHead; while (pResult != pNode){ pNode = pNode.next; pResult = pResult.next; } return pResult; }
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 洪雅县| 兴安县| 衢州市| 竹山县| 田阳县| 兰考县| 临桂县| 汶川县| 弥勒县| 阿拉善右旗| 海伦市| 白山市| 华安县| 肇州县| 阿城市| 伊宁县| 蒲城县| 泸定县| 临猗县| 始兴县| 张掖市| 咸丰县| 肃南| 七台河市| 铜梁县| 密山市| 交城县| 盖州市| 左权县| 晋州市| 墨江| 甘肃省| 波密县| 民勤县| 东安县| 扶余县| 云霄县| 灌阳县| 安龙县| 长武县| 大关县|