19. Remove Nth Node From End of List Leetcode Python

Given a linked list, remove the nth node from the end of list and return its head.


For example,


   Given linked list: 1->2->3->4->5, and n = 2.


   After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n will always be valid.

Try to do this in one pass.

这道题目最直接的想法是先把整个list走一遍知道长度,然后再走 用总长度减去所要的点,得到位置就跳过。这样需要走两边 用一个pointer 时间复杂度为O(2n)

l另外一种思路是用两个指针 fast 和slow。 fast先走n 步,slow这时候从头开始走,当fast走到尾的时候slow就走到需要跳过的位置了。

这样只需要走一遍就可以了。


Intuitively, the first idea we have is to iteratively go through the whole list and then count the length of the list. Then we deduct the required spot from the end. The result is the length we need to go from the beginning.

say the whole length is L we want to delete n from the end. we need to go L-n from the begining.

 This method will require us to go through the whole list for twice. The time complexity is O(2n) and require one pointer.


Another method will require two pointers. Fast and Slow. 

1. fast go n steps from the beginning.

2. slow start from the beginning.

3. when fast goes to the end of the list slow goes to the spot we want to delete.


code is as follow:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    # @return a ListNode
    def removeNthFromEnd(self, head, n):
        dummy=ListNode(0)
        dummy.next=head
        fast=dummy
        slow=dummy
        while n>0:
            fast=fast.next
            n-=1
        while fast.next:
            fast=fast.next
            slow=slow.next
        slow.next=slow.next.next
        return dummy.next
        
        


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值