[LeetCode]142. Linked List Cycle II

来源:互联网 发布:汽车cd刻录软件 编辑:程序博客网 时间:2024/05/03 13:21

Problem Description

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

Note: Do not modify the linked list.

Follow up:
Can you solve it without using extra space?
[https://leetcode.com/problems/linked-list-cycle-ii/]

思路

还是用两个指针,一个快一个慢,发现有圈之后,将一个指针扔回head,然后每个指针相同速度一格格走,再次相遇的地方就是圈的起点。
设圈前面有n个格,在圈里第x个格第一次相遇,圈的长度为y。
辣么!!2*(n+x)=n+x+y
辣么!!!n=y-x
y-x就是让一个点走回圈的起点!!
n是让一个点从起点走到圈的起点!!
就酱!

Code

package Q142;public class Solution {    static class ListNode {         int val;         ListNode next;         ListNode(int x) {             val = x;             next = null;         }     }    public static ListNode detectCycle(ListNode head) {        ListNode quick=head;        ListNode slow=head;        int mark=0;        if(head==null) return null;        while(quick.next!=null&&quick.next.next!=null){            quick=quick.next.next;            slow=slow.next;            if(quick==slow){                mark=1;                break;            }        }        if(mark==0) return null;        quick=head;        while(quick!=slow){            quick=quick.next;            slow=slow.next;        }        return slow;    }//  public static void main(String[] args){//      ListNode a1= new ListNode(1);//      ListNode a2= new ListNode(2);//      ListNode a3= new ListNode(3);//      ListNode a4= new ListNode(4);//      ListNode a5= new ListNode(5);//      ListNode a6= new ListNode(6);//      ListNode a7= new ListNode(7);//      ListNode a8= new ListNode(8);//      a1.next=a2;//      a2.next=a3;//      a3.next=a4;//      a4.next=a5;//      a5.next=a6;//      a6.next=a7;//      a7.next=a8;//      a8.next=a4;//      System.out.print(detectCycle(a1).val);//  }}
0 0
原创粉丝点击