# 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: ListNode
:type n: int
:rtype: ListNode
"""
dummy = ListNode()
dummy.next = head
curr = dummy
while curr:
temp = curr
for i in range(n+1):
temp = temp.next
if temp == None:
curr.next = curr.next.next
break
curr = curr.next
dummy = dummy.next
return dummy
This question can be done in several direct way. For example Iterating the linked list and store the location in a extra array, but this will lead to extra space consumption for O(m) while m equal to length of linked list. Another approach is like the code above to verifying while iterating; each time we visit the node, we use a for loop and a temp variable to verify whether the current node is the target node. However, this method is less efficient in time complexity.
The following method is an improved version of above method, instead we verifying while iterating, we use a two pointers, fast and slow, to pre_allocate the gap, which to replace the verifying action done by the for loop in the previous method.
# 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: ListNode
:type n: int
:rtype: ListNode
"""
dummy = ListNode()
dummy.next = head
fast = dummy
slow = dummy
for i in range(n+1):
fast = fast.next
while fast != None:
fast = fast.next
slow = slow.next
slow.next = slow.next.next
return dummy.next
the two pointers method is highly efficient in time.