From d865e65e7c0d5e817d4bbeb57234aff7faa57f4f Mon Sep 17 00:00:00 2001 From: spencerkrebs Date: Sat, 2 May 2026 14:01:36 -0400 Subject: [PATCH] cycle --- linked-list-cycle-ii.py | 32 ++++++++++++++++++++++++++++++++ nth-node.py | 18 ++++++++++++++++++ reverse-linked-list.py | 33 +++++++++++++++++++++++++++++++++ 3 files changed, 83 insertions(+) create mode 100644 linked-list-cycle-ii.py create mode 100644 nth-node.py create mode 100644 reverse-linked-list.py diff --git a/linked-list-cycle-ii.py b/linked-list-cycle-ii.py new file mode 100644 index 00000000..96601f1b --- /dev/null +++ b/linked-list-cycle-ii.py @@ -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 \ No newline at end of file diff --git a/nth-node.py b/nth-node.py new file mode 100644 index 00000000..ba97926d --- /dev/null +++ b/nth-node.py @@ -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 \ No newline at end of file diff --git a/reverse-linked-list.py b/reverse-linked-list.py new file mode 100644 index 00000000..90897fe4 --- /dev/null +++ b/reverse-linked-list.py @@ -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 \ No newline at end of file