題目
給一個鏈表,若其中包含環(huán),請找出該鏈表的環(huán)的入口結(jié)點,否則,輸出null。
程序核心思想
- 第一種方法的思想非常簡單。使用一個hashset,遍歷每一個節(jié)點,如果其出現(xiàn)在hashset中,那么返回它,它就是環(huán)的入口節(jié)點。如果沒出現(xiàn),則添加到hashset中,直到遍歷完所有的(null),則返回null。
- 第二種方法是一個結(jié)論,記住就好了。
準備兩個指針,一個快指針一個慢指針,快指針一次走兩步,慢指針一次走一步,如果快指針走到null了,直接返回false,否則快慢指針一定會在環(huán)上相遇。當快慢指針相遇時,快指針回到鏈表的頭部,然后快指針從走兩步變?yōu)樽咭徊?,則快慢指針一定會在環(huán)的入口節(jié)點處相遇。
Tips

hashset的方法.png
代碼
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
*/
import java.util.HashSet;
public class Solution {
public ListNode EntryNodeOfLoop(ListNode pHead)
{
HashSet<ListNode> hs = new HashSet<ListNode>();
while(pHead != null){
if(hs.contains(pHead)){
return pHead;
}else{
hs.add(pHead);
}
pHead = pHead.next;
}
return null;
}
}
//LeetCode
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode detectCycle(ListNode head) {
if(head == null) return null;
ListNode fast = head;
ListNode slow = head;
if(head.next != null && head.next.next != null){
slow = head.next;
fast = slow.next;
}else{
return null;
}
while(fast.next != null && fast.next.next != null){
if(fast == slow){
fast = head;
while(fast != slow){
slow = slow.next;
fast = fast.next;
}
return fast;
}else{
slow = slow.next;
fast = fast.next.next;
}
}
return null;
}
}