From 09a218a36ab8a93d94cf0a247707cb6ed812456c Mon Sep 17 00:00:00 2001 From: Adithya Vinayak Date: Sat, 7 Mar 2026 23:07:02 -0500 Subject: [PATCH] working solution --- problem1.py | 17 +++++++++++++++++ problem2.py | 20 ++++++++++++++++++++ problem3.py | 28 ++++++++++++++++++++++++++++ 3 files changed, 65 insertions(+) create mode 100644 problem1.py create mode 100644 problem2.py create mode 100644 problem3.py diff --git a/problem1.py b/problem1.py new file mode 100644 index 00000000..95208641 --- /dev/null +++ b/problem1.py @@ -0,0 +1,17 @@ +# problem 1 +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: + if not head: + return None + prev = None + while(head): + temp = head.next + head.next = prev + prev = head + head = temp + return prev \ No newline at end of file diff --git a/problem2.py b/problem2.py new file mode 100644 index 00000000..8dc7f2e1 --- /dev/null +++ b/problem2.py @@ -0,0 +1,20 @@ +# problem 2 + +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]: + temp_head = ListNode(-1) + temp_head.next = head + slow_ptr = temp_head + fast_ptr = temp_head + for _ in range(n+1): + fast_ptr = fast_ptr.next + while(fast_ptr): + fast_ptr = fast_ptr.next + slow_ptr = slow_ptr.next + slow_ptr.next = slow_ptr.next.next + return temp_head.next \ No newline at end of file diff --git a/problem3.py b/problem3.py new file mode 100644 index 00000000..506d0e0d --- /dev/null +++ b/problem3.py @@ -0,0 +1,28 @@ +# problem 3 + +# 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 + match_flag = False + while(fast.next and fast.next.next): + fast=fast.next.next + slow=slow.next + if fast == slow: + match_flag = True + break + if not match_flag: + return None + slow = head + while slow!=fast: + slow = slow.next + fast = fast.next + return slow \ No newline at end of file