1 Star 0 Fork 0

表情扭曲 / leetcode

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
lc142.java 1.62 KB
一键复制 编辑 原始数据 按行查看 历史
liu13 提交于 2019-07-15 14:01 . 20190715
package code;
/*
* 142. Linked List Cycle II
* 题意:求链表环的起始节点
* 难度:Medium
* 分类:Linked List, Two Pointers
* 思路:lc141进一步问题。快慢指针相遇后走了a+b步,head 走a步后到起始点,则 a+b+n=2a+2b -> a+b=n 所以相遇点再走a步到起始点。相遇以后再设一个指针从head开始走,慢指针接着走,则相遇点为环的入口点。
* Tips:
*/
public class lc142 {
public class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
public ListNode detectCycle(ListNode head) {
if(head==null)
return null;
ListNode slow = head;
ListNode fast = head;
ListNode slow2 = head;
while( fast.next!=null && fast.next.next!=null ){
slow = slow.next;
fast = fast.next.next;
if(slow==fast){
while(slow2!=slow){
slow = slow.next;
slow2 = slow2.next;
}
return slow2;
}
}
return null;
}
public ListNode detectCycle2(ListNode head) {
if(head==null||head.next==null) return null;
ListNode slow = head;
ListNode fast = head.next;
while(fast!=null&&fast.next!=null){
slow = slow.next;
fast = fast.next.next;
if(slow==fast){
slow = slow.next;
while(head!=slow){
head = head.next;
slow = slow.next;
}
return slow;
}
}
return null;
}
}
1
https://gitee.com/abfantasy/leetcode.git
git@gitee.com:abfantasy/leetcode.git
abfantasy
leetcode
leetcode
master

搜索帮助

53164aa7 5694891 3bd8fe86 5694891