diff --git a/linked-list-cycle-ii.py b/linked-list-cycle-ii.py new file mode 100644 index 00000000..a2793652 --- /dev/null +++ b/linked-list-cycle-ii.py @@ -0,0 +1,28 @@ +''' +Time Complexity : O(m + n) +Space Complexity : O(1) +Did this code successfully run on Leetcode : Yes +Any problem you faced while coding this : No +''' +# Definition for singly-linked list. +class ListNode: + def __init__(self, x): + self.val = x + self.next = None + +class Solution: + def detectCycle(self, head): + 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: + fast = head + while slow != fast: + slow = slow.next + fast = fast.next + return slow + \ 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..d173ea5b --- /dev/null +++ b/remove-nth-node-from-end-of-list.py @@ -0,0 +1,31 @@ +''' +Time Complexity : O(n) +Space Complexity : O(1) +Did this code successfully run on Leetcode : Yes +Any problem you faced while coding this : No +''' +# 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, n): + if head is None: + return head + dummy = ListNode(0, head) + slow = dummy + fast = dummy + count = 0 + while count <= n: + fast = fast.next + count += 1 + + while fast is not None: + slow = slow.next + fast = fast.next + + slow.next = slow.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..2d846d7f --- /dev/null +++ b/reverse-linked-list.py @@ -0,0 +1,22 @@ +''' +Time Complexity : O(n) +Space Complexity : O(1) +Did this code successfully run on Leetcode : Yes +Any problem you faced while coding this : No +''' +# 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): + prev = None + curr = head + while curr: + fast = curr.next + curr.next = prev + prev = curr + curr = fast + + return prev \ No newline at end of file