题目链接
本题是对于上一题 leetcode141.环形链表 的扩展题目,在我的文章 链表相关基础题及答案解析 中,有关于这道题目的详细题解。在这里就不废话了,直接上代码:
/**
* 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 || head.next == null || head.next.next == null){
return null;
}
ListNode cur = head.next;
ListNode fast = head.next.next;
while(cur != fast){
if(fast.next == null || fast.next.next == null){
return null;
}
fast = fast.next.next;
cur = cur.next;
}
// 快指针回到头结点,改为每次走一步,再次与cur相遇的那个节点就是返回的节点
fast = head;
while(fast != cur){
fast = fast.next;
cur = cur.next;
}
return cur;
}
}
执行结果: