diff --git a/linked_list_cycle.py b/linked_list_cycle.py new file mode 100644 index 00000000..0b783740 --- /dev/null +++ b/linked_list_cycle.py @@ -0,0 +1,38 @@ +# // 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(object): +# def __init__(self, x): +# self.val = x +# self.next = None + +class Solution(object): + def detectCycle(self, head): + """ + :type head: ListNode + :rtype: ListNode + """ + fast=head + slow=head + cycle=False + + while(fast and fast.next): + slow=slow.next + fast=fast.next.next + if fast==slow: + cycle=True + break + + if cycle: + fast=head + while(fast!=slow): + fast=fast.next + slow=slow.next + else: + return None + return fast + + \ No newline at end of file diff --git a/remove_nth_node.py b/remove_nth_node.py new file mode 100644 index 00000000..7e19a90b --- /dev/null +++ b/remove_nth_node.py @@ -0,0 +1,34 @@ +# // Time Complexity : O(n) +# // Space Complexity : O(1) +# // Did this code successfully run on Leetcode : Yes +# // Any problem you faced while coding this : Easy to think of 2pass, but 1pass is tricky + +# Definition for singly-linked list. +class ListNode(object): + def __init__(self, val=0, next=None): + self.val = val + self.next = next +class Solution(object): + def removeNthFromEnd(self, head, n): + """ + :type head: Optional[ListNode] + :type n: int + :rtype: Optional[ListNode] + """ + temp=ListNode(0) + temp.next=head + c=0 + first=temp + second=temp + + while(c<=n): + second=second.next + c+=1 + + while(second): + first=first.next + second=second.next + + first.next=first.next.next + + return temp.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..fb24f546 --- /dev/null +++ b/reverse_linked_list.py @@ -0,0 +1,27 @@ +# // Time Complexity : O(n) +# // Space Complexity : O(n) - due to recursive call stack +# // Did this code successfully run on Leetcode : Yes +# // Any problem you faced while coding this : No + +# Definition for singly-linked list. +# class ListNode(object): +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution(object): + def reverseList(self, head): + """ + :type head: Optional[ListNode] + :rtype: Optional[ListNode] + """ + self.res=None + def helper(root): + if root==None or root.next==None: + self.res=root + return + helper(root.next) + root.next.next=root + root.next=None + + helper(head) + return self.res