diff --git a/Peroblem_3.py b/Peroblem_3.py new file mode 100644 index 00000000..d1bae6b2 --- /dev/null +++ b/Peroblem_3.py @@ -0,0 +1,20 @@ +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, x): +# self.val = x +# self.next = None + + +class Solution: + def detectCycle(self, head): + slow, fast = head, head + while fast and fast.next: + slow = slow.next + fast = fast.next.next + if fast == slow: + fast = head + while fast != slow: + fast = fast.next + slow = slow.next + return slow + return None diff --git a/Problem_1.py b/Problem_1.py new file mode 100644 index 00000000..168a6487 --- /dev/null +++ b/Problem_1.py @@ -0,0 +1,16 @@ +class ListNode: + def __init__(self, val=0, next=None): + self.val = val + self.next = next +class Solution: + def reverseList(self, head): + self.newHead = None + return self.helper(head) + + def helper(self, node): + if not node or not node.next: + return node + curr = self.helper(node.next) + node.next.next = node + node.next = None + return curr \ No newline at end of file diff --git a/Problem_2.py b/Problem_2.py new file mode 100644 index 00000000..8c6d73b3 --- /dev/null +++ b/Problem_2.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 +class Solution: + def removeNthFromEnd(self, head,n): + fast = head + for _ in range(n): + fast = fast.next + if not fast: + return head.next + slow = head + while fast.next: + slow = slow.next + fast = fast.next + slow.next = slow.next.next + return head