LeetCode | Linked List Cycle II
Given a linked list, return the node where the cycle begins. If there is no cycle, return null
.
Follow up: Can you solve it without using extra space?
/** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */
//思路:
首先利用快慢双指针向后遍历(slow每次向后一格,fast每次向后两格),当两个指针重合时,则list中一定存在cycle
然后让fast_pointer停在两指针相遇的位置,而让slow_pointer回到head,让两指针同步的每次向后遍历一格,则两指针相遇的node即为cycle begin的node(有点像单纯的智力题。。。)
public class Solution { public ListNode detectCycle(ListNode head) { if(head==null || head.next==null) return null; ListNode slow_pointer = head; ListNode fast_pointer = head; boolean hasCycle = false; while(fast_pointer!=null && fast_pointer.next!=null){ //判断list中是否有cycle的存在,思路与昨天的题一样 slow_pointer = slow_pointer.next; fast_pointer = fast_pointer.next.next; if(slow_pointer == fast_pointer){ hasCycle = true; break; //注意:此处要有break,否则两个pointer会在cycle中一直遍历下去,无限循环 } } if(hasCycle){ slow_pointer = head; while(true){ if(slow_pointer == fast_pointer) return slow_pointer; slow_pointer = slow_pointer.next; fast_pointer = fast_pointer.next; //if(slow_pointer == fast_pointer) return slow_pointer; 注:判断的语句不能放在后边,不然当list中tail.next=head时会出错 } } return null; } }