File tree 5 files changed +89
-0
lines changed
algorithms/LinkedListCycle
5 files changed +89
-0
lines changed Original file line number Diff line number Diff line change @@ -139,6 +139,7 @@ All solutions will be accepted!
139
139
| 290| [ Word Pattern] ( https://leetcode-cn.com/problems/word-pattern/description/ ) | [ java/py/js] ( ./algorithms/WordPattern ) | Easy|
140
140
| 205| [ Isomorphic Strings] ( https://leetcode-cn.com/problems/isomorphic-strings/description/ ) | [ java/py/js] ( ./algorithms/IsomorphicStrings ) | Easy|
141
141
| 125| [ Valid Palindrome] ( https://leetcode-cn.com/problems/valid-palindrome/description/ ) | [ java/py/js] ( ./algorithms/ValidPalindrome ) | Easy|
142
+ | 141| [ Linked List Cycle] ( https://leetcode-cn.com/problems/linked-list-cycle/description/ ) | [ java/py/js] ( ./algorithms/LinkedListCycle ) | Easy|
142
143
143
144
# Database
144
145
| #| Title| Solution| Difficulty|
Original file line number Diff line number Diff line change
1
+ # Linked List Cycle
2
+ This problem is easy to solve by double pointer
Original file line number Diff line number Diff line change
1
+ /**
2
+ * Definition for singly-linked list.
3
+ * class ListNode {
4
+ * int val;
5
+ * ListNode next;
6
+ * ListNode(int x) {
7
+ * val = x;
8
+ * next = null;
9
+ * }
10
+ * }
11
+ */
12
+ public class Solution {
13
+ public boolean hasCycle (ListNode head ) {
14
+ ListNode p1 = head ,
15
+ p2 = head ;
16
+
17
+ while (p1 != null && p2 != null ) {
18
+ p1 = p1 .next ;
19
+ p2 = p2 .next ;
20
+ if (p2 != null && p2 .next != null ) {
21
+ if (p1 == p2 .next ) {
22
+ return true ;
23
+ } else {
24
+ p2 = p2 .next ;
25
+ }
26
+ }
27
+ }
28
+
29
+ return false ;
30
+ }
31
+ }
Original file line number Diff line number Diff line change
1
+ /**
2
+ * Definition for singly-linked list.
3
+ * function ListNode(val) {
4
+ * this.val = val;
5
+ * this.next = null;
6
+ * }
7
+ */
8
+
9
+ /**
10
+ * @param {ListNode } head
11
+ * @return {boolean }
12
+ */
13
+ var hasCycle = function ( head ) {
14
+ let p1 = head ,
15
+ p2 = head
16
+
17
+ while ( p1 && p2 ) {
18
+ p1 = p1 . next
19
+ p2 = p2 . next
20
+ if ( p2 && p2 . next ) {
21
+ if ( p1 === p2 . next ) {
22
+ return true
23
+ } else {
24
+ p2 = p2 . next
25
+ }
26
+ }
27
+ }
28
+
29
+ return false
30
+ } ;
Original file line number Diff line number Diff line change
1
+ # Definition for singly-linked list.
2
+ # class ListNode(object):
3
+ # def __init__(self, x):
4
+ # self.val = x
5
+ # self.next = None
6
+
7
+ class Solution (object ):
8
+ def hasCycle (self , head ):
9
+ """
10
+ :type head: ListNode
11
+ :rtype: bool
12
+ """
13
+ p1 = head
14
+ p2 = head
15
+
16
+ while p1 and p2 :
17
+ p1 = p1 .next
18
+ p2 = p2 .next
19
+ if p2 and p2 .next :
20
+ if p1 == p2 .next :
21
+ return True
22
+ else :
23
+ p2 = p2 .next
24
+
25
+ return False
You can’t perform that action at this time.
0 commit comments