File tree 3 files changed +83
-1
lines changed
src/com/andavid/leetcode/_141
3 files changed +83
-1
lines changed Original file line number Diff line number Diff line change 50
50
| 206 | [ Reverse Linked List] [ 206 ] |
51
51
| 21 | [ Merge Two Sorted Lists] [ 021 ] |
52
52
| 234 | [ Palindrome Linked List] [ 234 ] |
53
-
53
+ | 141 | [ Linked List Cycle ] [ 141 ] |
54
54
55
55
** 其他**
56
56
90
90
[ 206 ] : https://github.com/andavid/leetcode-java/blob/master/note/206/README.md
91
91
[ 021 ] : https://github.com/andavid/leetcode-java/blob/master/note/021/README.md
92
92
[ 234 ] : https://github.com/andavid/leetcode-java/blob/master/note/234/README.md
93
+ [ 141 ] : https://github.com/andavid/leetcode-java/blob/master/note/141/README.md
Original file line number Diff line number Diff line change
1
+ # [ Linked List Cycle] [ title ]
2
+
3
+ ## Description
4
+
5
+ Given a linked list, determine if it has a cycle in it.
6
+
7
+ Follow up:
8
+ Can you solve it without using extra space?
9
+
10
+ ## 思路
11
+
12
+ 使用快慢两个指针,慢指针每次前进一步,快指针每次前进两步,如果慢指针和快指针相等,说明有环。
13
+
14
+
15
+ ## [ 完整代码] [ src ]
16
+
17
+ ``` java
18
+ /**
19
+ * Definition for singly-linked list.
20
+ * class ListNode {
21
+ * int val;
22
+ * ListNode next;
23
+ * ListNode(int x) {
24
+ * val = x;
25
+ * next = null;
26
+ * }
27
+ * }
28
+ */
29
+ public class Solution {
30
+ public boolean hasCycle (ListNode head ) {
31
+ ListNode slow = head;
32
+ ListNode fast = head;
33
+ while (fast != null && fast. next != null ) {
34
+ slow = slow. next;
35
+ fast = fast. next. next;
36
+ if (slow == fast) {
37
+ return true ;
38
+ }
39
+ }
40
+ return false ;
41
+ }
42
+ }
43
+ ```
44
+
45
+ [ title ] : https://leetcode.com/problems/linked-list-cycle
46
+ [ src ] : https://github.com/andavid/leetcode-java/blob/master/src/com/andavid/leetcode/_141/Solution.java
Original file line number Diff line number Diff line change
1
+ class Solution {
2
+
3
+ public static boolean hasCycle (ListNode head ) {
4
+ ListNode slow = head ;
5
+ ListNode fast = head ;
6
+ while (fast != null && fast .next != null ) {
7
+ slow = slow .next ;
8
+ fast = fast .next .next ;
9
+ if (slow == fast ) {
10
+ return true ;
11
+ }
12
+ }
13
+ return false ;
14
+ }
15
+
16
+ public static class ListNode {
17
+ int val ;
18
+ ListNode next ;
19
+ ListNode (int x ) {
20
+ val = x ;
21
+ }
22
+ }
23
+
24
+ public static void main (String [] args ) {
25
+ ListNode node1 = new ListNode (1 );
26
+ ListNode node2 = new ListNode (2 );
27
+ ListNode node3 = new ListNode (3 );
28
+ node1 .next = node2 ;
29
+ node2 .next = node3 ;
30
+ node3 .next = node1 ;
31
+
32
+ System .out .println (hasCycle (node1 ));
33
+ }
34
+
35
+ }
You can’t perform that action at this time.
0 commit comments