Quoestion: ClickHere
Algorithm:
step1:intialize slow and fast pointers with head
step2:Move forward fast pointer by n positions
step3:if fast.next is None then return head.next
step4:Move forward fast and slow pointers by one step until fast.next == None.
step5:slow.next = slow.next.next
Python Code
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
slow = fast = head
for i in range(n):
print(fast.val)
fast = fast.next
if fast is None:
return head.next
while fast.next:
print(fast.val,slow.val)
fast= fast.next
slow = slow.next
slow.next = slow.next.next
return head
Algorithm:
step1:intialize slow and fast pointers with head
step2:Move forward fast pointer by n positions
step3:if fast.next is None then return head.next
step4:Move forward fast and slow pointers by one step until fast.next == None.
step5:slow.next = slow.next.next
Python Code
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
slow = fast = head
for i in range(n):
print(fast.val)
fast = fast.next
if fast is None:
return head.next
while fast.next:
print(fast.val,slow.val)
fast= fast.next
slow = slow.next
slow.next = slow.next.next
return head
0 Comments