题目:
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?
分析:
给定一个链表,返回这个链表中环的开始,若无环,那么返回null,并且不能有额外的空间。首先需要判断是否有环,定义两个指针slow和fast,slow每次前进一格,fast每次前进
两格,如果有环,那么这两个指针必然会相遇;如果没有环,那么直接返回null即可;在有环的情况下,将slow指针指向相遇节点,将fast指针指向开始节点,继续前进,这时两个
指针每次前进一格,当指针再次相遇的时候,就是环开始的位置。
具体代码如下:
/**
* 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 meeting = meetingNode(head);
if (meeting == null)
return null;
ListNode fast = head;
ListNode slow = meeting;
while(slow != fast){
fast = fast.next;
slow = slow.next;
}
return fast;
}
public ListNode meetingNode(ListNode head){
if(head == null || head.next == null)
return null;
ListNode slow = head;
ListNode fast = head;
while(fast.next != null && fast.next.next != null){
slow = slow.next;
fast = fast.next.next;
if (slow == fast)
return slow;
}
return null;
}
}