您的位置:首页 > 编程语言 > Java开发

[leetcode]142. Linked List Cycle II@Java解题报告

2017-08-18 12:18 429 查看
https://leetcode.com/problems/linked-list-cycle-ii/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?

思路:本题与 Linked List Cycle 类似,一样是申请两个指针slow和fast

slow指针一次走一步,fast走两步。

现在假设存在环,设从head走A步到达环的入口节点,第一次相遇时,slow在环内走了B步(slow一共走了A+B步),

当fast和slow指针第一次相遇时,slow走了A+B步,那么fast走过的距离是slow的两倍,即2*(A+B),、

此时,fast和slow的距离正好相差一个环的距离,即2*(A+B)=A+B+C(设C为环的大小),得C=A+B

此时,slow只要再走C-B步就可以走到环的入口(因为环的大小是C,slow已经在环内走了B步),有由C=A+B得到C-B=A,

即,如果此时有一个新的指针node,从head出发,当slow和head相遇时,相遇的点就是环的入口点

package go.jacob.day818;

/**
* 142. Linked List Cycle II
*
* @author Jacob 题意:删除环的第一个节点,不存在环则返回null
*/
public class Demo2 {
public ListNode detectCycle(ListNode head) {
if (head == null)
return null;
ListNode slow = head;
ListNode fast = head;
while (fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
//slow被fast追上
if(slow==fast){
//从头结点出发
ListNode node=head;
while(node!=slow){
node=node.next;
slow=slow.next;
}
return node;
}
}
return null;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: