diff --git a/Problem1.py b/Problem1.py new file mode 100644 index 00000000..0f78be9e --- /dev/null +++ b/Problem1.py @@ -0,0 +1,28 @@ +#Problem 206. REVERSE LINKED LIST +# TIME COMPELXITY: O(N) where N denotes the number of nodes in the given linked list +# SPACE COMPLEXITY: O(N) since we are doing recursion which will be having stack logic + + + +# 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] + """ + return self.helper(head,None) + + def helper(self,curr,prev): + if curr is None: + return prev + + temp=curr.next + curr.next=prev + prev=curr + curr=temp + return self.helper(curr,prev) \ No newline at end of file diff --git a/Problem2.py b/Problem2.py new file mode 100644 index 00000000..90199f5f --- /dev/null +++ b/Problem2.py @@ -0,0 +1,38 @@ +#Problem 19. REMOVE NTH NODE FROM END OF LIST +# TIME COMPELXITY: O(N) where N denotes the number of nodes present +# SPACE COMPLEXITY: O(1) as we are using pointers + + +# 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] + """ + dummy=ListNode(-1) + dummy.next=head + counter=0 + fast=dummy + slow=dummy + + while counter<=n: + fast=fast.next + counter+=1 + + while fast is not None: + slow=slow.next + fast=fast.next + + # temp = slow.next + # slow.next = slow.next.next + # temp.next = None + + slow.next = slow.next.next + + return dummy.next diff --git a/Problem3.py b/Problem3.py new file mode 100644 index 00000000..8625c228 --- /dev/null +++ b/Problem3.py @@ -0,0 +1,41 @@ +#Problem 142. LINKED LIST CYCLE II +# TIME COMPELXITY: O(N) where N denotes the number of nodes +# SPACE COMPLEXITY: O(1) as we are not using any extra space we are only using pointers which takes O(1) of space + + +# 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 + """ + + if head is None: + return None + fast=head + slow=head + flag=False + + while fast.next is not None and fast.next.next is not None: + slow=slow.next + fast=fast.next.next + + if slow==fast: + flag=True + break + + if not flag: + return None + + slow=head + while slow!=fast: + slow=slow.next + fast=fast.next + + return slow \ No newline at end of file