Skip to content

Commit e5cb25a

Browse files
solves linked list cycle
1 parent 53566f0 commit e5cb25a

File tree

2 files changed

+22
-1
lines changed

2 files changed

+22
-1
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@
4242
| 122 | [Best Time to Buy and Sell Stocks II](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/BestTimeToBuyAndSellStockII.java) [![Python](https://img.icons8.com/color/35/000000/python.png)](python/best_time_to_buy_and_sell_stock_ii.py) |
4343
| 125 | [Valid Palindrome](https://leetcode.com/problems/valid-palindrome) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/ValidPalindrome.java) [![Python](https://img.icons8.com/color/35/000000/python.png)](python/valid_palindrome.py) |
4444
| 136 | [Single Number](https://leetcode.com/problems/single-number) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/SingleNumber.java) [![Python](https://img.icons8.com/color/35/000000/python.png)](python/single_number.py) |
45-
| 141 | [Linked List Cycle](https://leetcode.com/problems/linked-list-cycle) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/LinkedListCycle.java) |
45+
| 141 | [Linked List Cycle](https://leetcode.com/problems/linked-list-cycle) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/LinkedListCycle.java) [![Python](https://img.icons8.com/color/35/000000/python.png)](python/linked_list_cycle.py) |
4646
| 155 | [Min Stack](https://leetcode.com/problems/min-stack) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/MinStack.java) |
4747
| 157 | [Read N Characters Given Read4](https://leetcode.com/problems/read-n-characters-given-read4) | Easy | |
4848
| 160 | [Intersection of Two Linked Lists](https://leetcode.com/problems/intersection-of-two-linked-lists) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](src/IntersectionOf2LinkedLists.java) |

python/linked_list_cycle.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# Definition for singly-linked list.
2+
class ListNode:
3+
def __init__(self, x):
4+
self.val = x
5+
self.next = None
6+
7+
8+
class Solution:
9+
def not_null(self, head: ListNode) -> bool:
10+
return head is not None
11+
12+
def hasCycle(self, head: ListNode) -> bool:
13+
if head is None:
14+
return False
15+
slow, fast = head, head.next
16+
while self.not_null(slow) and self.not_null(fast) and self.not_null(slow.next) and self.not_null(fast.next):
17+
if slow is fast:
18+
return True
19+
slow = slow.next
20+
fast = fast.next.next
21+
return False

0 commit comments

Comments
 (0)