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
38 changes: 38 additions & 0 deletions linked_list_cycle.py
Original file line number Diff line number Diff line change
@@ -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


34 changes: 34 additions & 0 deletions remove_nth_node.py
Original file line number Diff line number Diff line change
@@ -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
27 changes: 27 additions & 0 deletions reverse_linked_list.py
Original file line number Diff line number Diff line change
@@ -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