19. Remove Nth Node From End of List

移除链表倒数第n个节点。

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.

另外,题目要求遍历一遍完成。

我的思路是这样的:

扫描一遍链表s,构建一个长度为n+1的列表l,列表中的元素依次是原链表中的len(s) - n个元素到最后一个元素。

例如:s:1->2->3->4->5, n=2

那么:l:[3,4,5]

再将列表中的l[0]指向l[2]

 1 # Definition for singly-linked list.
 2 # class ListNode:
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.next = None
 6 
 7 class Solution:
 8     def removeNthFromEnd(self, head, n):
 9         """
10         :type head: ListNode
11         :type n: int
12         :rtype: ListNode
13         """
14         if head.next is None:
15             return None
16         tmp = [head, ]
17         nxt = head.next
18         while nxt is not None:
19             tmp.append(nxt)
20             if len(tmp) > n + 1:
21                 tmp.remove(tmp[0])
22             nxt = nxt.next
23         if len(tmp) < n + 1:
24             return head.next
25         if n == 1:
26             tmp[0].next = None
27         else:
28             tmp[0].next = tmp[2]
29         return head

 

转载于:https://www.cnblogs.com/Luohys/p/10620161.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值