Skip to content

Commit afce607

Browse files
committed
solve problem Linked List Cycle
1 parent 58256df commit afce607

File tree

5 files changed

+89
-0
lines changed

5 files changed

+89
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,7 @@ All solutions will be accepted!
139139
|290|[Word Pattern](https://leetcode-cn.com/problems/word-pattern/description/)|[java/py/js](./algorithms/WordPattern)|Easy|
140140
|205|[Isomorphic Strings](https://leetcode-cn.com/problems/isomorphic-strings/description/)|[java/py/js](./algorithms/IsomorphicStrings)|Easy|
141141
|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|
142143

143144
# Database
144145
|#|Title|Solution|Difficulty|

algorithms/LinkedListCycle/README.md

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
# Linked List Cycle
2+
This problem is easy to solve by double pointer
+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
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+
}
+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
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+
};
+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
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

0 commit comments

Comments
 (0)