Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions LinkedListCycle2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# Time Complexity : O(n)
# Space Complexity : O(1)
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : No
# Approach : Use two pointers moving at different speeds to check if there’s a cycle.
# If they meet, reset one to the head and walk both one step at a time.
# They meet again at the node where the cycle starts.

# 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]:
if head is None:
return None

slow, fast = head, 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



32 changes: 32 additions & 0 deletions RemoveNthNode.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# Time Complexity : O(n)
# Space Complexity : O(1)
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : No
# Approach : Move fast pointer n + 1 steps ahead so it leads the slow by n nodes.
# Then increment both together until fast hits the end — now slow is right before the target.
# Skip the node to be removed and clean up the reference.

# 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]:
dummy = ListNode(-1)
dummy.next = head
slow, fast = dummy, dummy

for i in range(n+1):
fast = fast.next

while fast is not None:
slow = slow.next
fast = fast.next

temp = slow.next
slow.next = slow.next.next
temp.next = None

return dummy.next

28 changes: 28 additions & 0 deletions ReverseLinkedList.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# Time Complexity : O(n)
# Space Complexity : O(1)
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : No
# Approach : Flip the direction of the pointer to the previous node.

# 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: Optional[ListNode]) -> Optional[ListNode]:
if head is None:
return None

prev, curr = None, head

while curr:
temp = curr.next
curr.next = prev
prev = curr
curr = temp

return prev