diff --git a/Problem1.py b/Problem1.py new file mode 100644 index 00000000..3fb5af75 --- /dev/null +++ b/Problem1.py @@ -0,0 +1,18 @@ +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next + +# Time Complexity --> O(n) +# Space Complexity --> O(1) +class Solution: + def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: + prev = None + curr = head + while curr is not None: + temp = curr.next + curr.next = prev + prev = curr + curr = temp + return prev diff --git a/Problem2.py b/Problem2.py new file mode 100644 index 00000000..8cda742f --- /dev/null +++ b/Problem2.py @@ -0,0 +1,27 @@ +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next + +# Time Complexity --> O(n) +# Space Complexity --> O(1) +class Solution: + def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]: + dummy = ListNode(None) + dummy.next = head + slow, fast = dummy, dummy + + count = 0 + while count<=n: + count += 1 + fast = fast.next + + while fast is not None: + fast = fast.next + slow = slow.next + temp = slow.next + slow.next = slow.next.next + temp.next = None + + return dummy.next diff --git a/Problem3.py b/Problem3.py new file mode 100644 index 00000000..35cf72c6 --- /dev/null +++ b/Problem3.py @@ -0,0 +1,26 @@ +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, x): +# self.val = x +# self.next = None + +# Time Complexity --> O(n) +# Space Complexity --> O(1) +class Solution: + def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]: + slow = head + fast = head + + while fast is not None and fast.next is not None: + slow = slow.next + fast = fast.next.next + if slow == fast: + break + + if fast is None or fast.next is None: + return None + fast = head + while slow!=fast: + slow = slow.next + fast = fast.next + return slow