Skip to content

Commit 1c6b67c

Browse files
committed
142. Linked List Cycle II
1 parent 8cac56d commit 1c6b67c

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
public class Solution {
2+
public ListNode detectCycle(ListNode head) {
3+
if(head == null){
4+
return null;
5+
}
6+
ListNode slow = head,fast = head;
7+
while(fast != null && fast.next != null){
8+
slow = slow.next;
9+
10+
fast = fast.next.next;
11+
12+
if(slow == fast){
13+
ListNode cur = head;
14+
while(cur != slow){
15+
cur = cur.next;
16+
slow = slow.next;
17+
}
18+
return cur;
19+
}
20+
}
21+
return null;
22+
}
23+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
public class TestCase {
2+
3+
public static void main(String[] args) {
4+
// ListNode listNode = new ListNode(3);
5+
// ListNode listNode1 = new ListNode(2);
6+
// ListNode listNode2 = new ListNode(0);
7+
// ListNode listNode3 = new ListNode(-4);
8+
// listNode.next = listNode1;
9+
// listNode1.next = listNode2;
10+
// listNode2.next = listNode3;
11+
// listNode3.next = listNode1;
12+
ListNode listNode = new ListNode(0);
13+
ListNode listNode1 = new ListNode(0);
14+
listNode1.next = listNode;
15+
listNode.next = listNode1;
16+
Solution solution = new Solution();
17+
ListNode result = solution.detectCycle(listNode);
18+
System.out.println(result.val);
19+
}
20+
}

0 commit comments

Comments
 (0)