From ca43220e190e9c0790735f65c26f590130a4282c Mon Sep 17 00:00:00 2001 From: anuragparla Date: Thu, 25 Jun 2026 11:25:44 -0400 Subject: [PATCH] feat: Linked List 1 complete --- LinkedlistcycleII.py | 38 ++++++++++++++++++++++++ remove_nth_node_from_end_of_list.py | 28 ++++++++++++++++++ reverse_linked_list.py | 45 +++++++++++++++++++++++++++++ 3 files changed, 111 insertions(+) create mode 100644 LinkedlistcycleII.py create mode 100644 remove_nth_node_from_end_of_list.py create mode 100644 reverse_linked_list.py diff --git a/LinkedlistcycleII.py b/LinkedlistcycleII.py new file mode 100644 index 00000000..3beccbdb --- /dev/null +++ b/LinkedlistcycleII.py @@ -0,0 +1,38 @@ +''' +Time: O(N) +Space: O(1) +''' + +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, x): +# self.val = x +# self.next = None + +class Solution: + def isCycle(self,slow,fast): + while fast and fast.next: + slow = slow.next + fast = fast.next.next + if slow == fast: + return [True, fast] + return [False, fast] + + def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]: + slow = fast = head + cycle = self.isCycle(slow,fast) + fast = cycle[1] + if cycle[0]: + while slow != fast: + slow = slow.next + fast = fast.next + return slow + return None + + + + + + + + \ No newline at end of file diff --git a/remove_nth_node_from_end_of_list.py b/remove_nth_node_from_end_of_list.py new file mode 100644 index 00000000..b6b1b583 --- /dev/null +++ b/remove_nth_node_from_end_of_list.py @@ -0,0 +1,28 @@ +''' +Time complexity: O(N) +Space complexity: O(1) +''' +# Definition for singly-linked list. +class ListNode: + def __init__(self, x): + self.val = x + self.next = None + +class Solution: + class Solution: + def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]: + dummyNode = ListNode(0,head) + slow = dummyNode + fast = head + + while fast and n > 0: + fast = fast.next + n -= 1 + + while fast: + slow = slow.next + fast = fast.next + + slow.next = slow.next.next + + return dummyNode.next diff --git a/reverse_linked_list.py b/reverse_linked_list.py new file mode 100644 index 00000000..b924196f --- /dev/null +++ b/reverse_linked_list.py @@ -0,0 +1,45 @@ +''' +Iterrative method: +time complexity: O(N) +space complexity: O(1) + +Recursive method: +time complexity: O(N) +space complexity: O(N) +''' +class ListNode: + def __init__(self, val=0, next=None): + self.val = val + self.next = next +class Solution: + # iterative way + def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: + if not head or head.next: + return head + prev = None + curr = head + next = None + + while curr: + next = curr.next + prev = curr.next + prev = curr + curr = next + return prev + + #recursive way + def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: + if not head or not head.next: + return head + + new_head = self.reverseList(head.next) + head.next.next = head + head.next = None + return new_head + + + + + + +