Skip to content
Open

cycle #1786

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions linked-list-cycle-ii.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None

class Solution:
def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
if not head:
return None
slow = head
fast = head
found=False
while fast and fast.next:
fast = fast.next.next
slow = slow.next
if fast == slow:
found=True
break
# slow and fast will always meet within the first cycle
if not found:
return None

pointer = head
while pointer != slow:
pointer = pointer.next
slow = slow.next

return pointer


# O(n) time, O(1) space
18 changes: 18 additions & 0 deletions nth-node.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# O(n) time, O(1) space
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
dummy = ListNode(0,head)
right = dummy
left = dummy

for i in range(n):
right = right.next


while right.next:
left = left.next
right = right.next

left.next = left.next.next

return dummy.next
33 changes: 33 additions & 0 deletions reverse-linked-list.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# O(n) time, O(1) space
class Solution:
def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
prev = None
cur = head
while cur:
temp = cur.next
cur.next = prev
prev = cur
cur = temp
return prev



# reverse linked list with recursion - O(n) time, O(1) space
# recursion stack:
# f(none)
# f(5)
# f(4)
# f(3)
# f(2)
# f(1)
class Solution:
def reverseList(self,head):
if head is None or head.next is None:
return head

# result is in global, not a parameter of recursion
result = self.reverseList(head.next) # return to returns to the same place from where we called it
# 5 5 5 5 5
head.next.next = head
head.next = None
return result