19. Remove Nth Node From End of List

# 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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值