题意:
不可更改链表节点,给定链表表头,返回链表在环中的第一个节点,没有返回null
题解:哈希表集合
遍历一遍链表,哈希表集合维护链表节点,当访问到的当前节点已经在集合中,说明当前节点是所求节点
哈希表集合解代码
/**
* 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) {
Set<ListNode> set = new HashSet<>();
while(head != null) {
if(set.contains(head)) return head;
set.add(head);
head = head.next;
}
return null;
}
}
题解2:双指针
慢指针:slow->每次移动一步
快指针:fast->每次移动两步
规律:
如果存在环,两个指针一定会相遇
第一次相遇时,使快指针指向head节点,两个指针都每次移动一步,再次相遇时则为环起点
双指针代码
/**
* 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) {
ListNode fast, slow;
slow = fast = head;
while(true) {
if(fast == null || fast.next == null) return null;
fast = fast.next.next;
slow = slow.next;
if(slow == fast) break;
}
fast = head;
while(fast != slow) {
fast = fast.next;
slow = slow.next;
}
return fast;
}
}