题目描述
给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null。
思路
题目明确给出链表包含环,也就是说明该链表不存在指向 NULL 的末尾结点
Hash表:
遍历链表并将每个节点添加到hash表中,直到有重复的Node节点,返回该结点
快慢指针:
定义慢指针p1,快指针p2。
p1一次走一步,p2一次走两步。直到p1 p2相遇后
p2返回链表头结点,然后p2也降为慢指针, p1 p2在同时走
p1 p2再次相遇后,返回该Node结点为入环结点
Hash表实现
Hash表具体代码
// Hash表
public class Solution {
public ListNode EntryNodeOfLoop(ListNode pHead){
// 代码的鲁棒性
if (pHead == null){
return null;
}
HashSet<ListNode> set = new HashSet<>();
while (pHead != null){
if (set.contains(pHead)){
return pHead;
}
set.add(pHead);
pHead = pHead.next;
}
return null;
}
}
快慢指针
快慢指针具体代码
// 快慢指针
public class Solution {
public ListNode EntryNodeOfLoop(ListNode pHead){
// 代码的鲁棒性
if (pHead == null || pHead.next == null || pHead.next.next == null){
return null;
}
// 慢指针
ListNode low = pHead.next;
// 快指针
ListNode fast = pHead.next.next;
while (fast != low){
// 当有指向null的直接返回
if (low.next == null || fast.next.next == null){
return null;
}
// 慢指针走一步
low = low.next;
// 快指针走两步
fast = fast.next.next;
}
// 快指针返回头结点
fast = pHead;
// 快指针和慢指针同时走
while (fast != low){
fast = fast.next;
low = low.next;
}
return low;
}
}
NowCoder(Online Coding, Please Click)