diff --git a/W4_6_reverse_linkedlist_three_pointer.py b/W4_6_reverse_linkedlist_three_pointer.py new file mode 100644 index 00000000..c6ed501a --- /dev/null +++ b/W4_6_reverse_linkedlist_three_pointer.py @@ -0,0 +1,22 @@ +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next + +# Time complexity: O(N), we visit all nodes with curr exactly once. +# Space complexity: O(1), we just use a few extra pointers (prev, curr, temp) + +class Solution: + def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: + prev = None + curr = head + + while curr != None: + temp = curr.next # Store curr.next before overiding. + curr.next = prev + prev = curr + curr = temp # Moving curr to the next node to process + + return prev + diff --git a/W4_7_cycle_linkedlist.py b/W4_7_cycle_linkedlist.py new file mode 100644 index 00000000..98605f9c --- /dev/null +++ b/W4_7_cycle_linkedlist.py @@ -0,0 +1,29 @@ +# 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]: + slow = head + fast = head + + while fast and fast.next: + slow = slow.next + fast = fast.next.next + + if slow == fast: + start = head + + while start != slow: + start = start.next + slow = slow.next + + return start + + return None + +# Time complexity O(N) +# Space complexity O(1) + diff --git a/W4_8_delete_nth_last_node_linkedlist.py b/W4_8_delete_nth_last_node_linkedlist.py new file mode 100644 index 00000000..9eef9414 --- /dev/null +++ b/W4_8_delete_nth_last_node_linkedlist.py @@ -0,0 +1,43 @@ +# 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]: + + length = 0 + curr = head + prev = head + + # Get the length of the linkedlist + while curr: + curr = curr.next + length = length + 1 + + # Get the position of the node to be deleted + del_index = (length - n) + + # for cases with difference 0, removing the head. + if del_index == 0: + return head.next + + prev = head + + while del_index > 1: + prev = prev.next + del_index -= 1 + + curr = prev.next + + # Swaping the links to delete targetnode + temp = curr.next + curr.next = None + prev.next = temp + + return head + +# Time complexity: O(2N) = O(N) +# Space complexity: O(1) + +