【leetcode解题历程与思考】19.Remove Nth Node From End of List

这个问题其实是比较简单的,我的思路是,把最后N+1个节点保存下来,链表遍历完之后,直接操作之前保存节点的最早一个即可。PS:经试验,python里面的List结构,存是的指针,而不是COPY,所以可以直接对list进行操作来改变原始数据。
我的代码:

class ListNode:
     def __init__(self, x):
         self.val = x
         self.next = None

class Solution:
    def removeNthFromEnd(self, head, n):
        """
        :type head: ListNode
        :type n: int
        :rtype: ListNode
        """
        buf = []
        cur = head
        i = 0
        while cur.next != None:
            if i < n:
                buf.append(cur)
            else:
                buf[i%n] = cur
            cur = cur.next
            i += 1                      #i is the number of nodes - 1

        if i == 0:
            return None

        if n == 1:
            buf[i % n].next = None
        elif n == 2: 
            if i == 1:
                head = cur
            else:
                buf[i % n].next = cur
        elif n == i + 1:
            head = buf[1]
        else:
            buf[i%n].next = buf[(i+2)%n]
        return head

效率在结果里面占了中位数,后来看到某大神的答案,代码更为简洁,使用了fast和slow两个指针来遍历链表,fast和slow中间相隔N,fast遍历完之后,slow的位置就是要操作的位置了,对大神代码进行优化后,代码:

class Solution:
    def removeNthFromEnd(self, head, n):
        """
        :type head: ListNode
        :type n: int
        :rtype: ListNode
        """
        fast, slow = head, head
        
        for _ in range(n):
            fast = fast.next
            
        if fast is None:
            return slow.next
        
        while fast.next:
            fast = fast.next
            slow = slow.next
        slow.next = slow.next.next
        return head

Good Luck, and have a nice day!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值