python - 从列表末尾删除第 N 个节点(Leetcode)?- Python
问题描述
链接 - https://leetcode.com/problems/remove-nth-node-from-end-of-list/
我的方法:
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
h = head
td = h
c = 0
while head.next is not None:
c+=1
print(c,n)
if c>n:
td = td.next
head = head.next
if c + 1 != n:
td.next = td.next.next
return h
它在 [1,2] 和 n = 2 之类的边界情况下失败,有什么方法可以修改它以使其适用于所有边界情况并被接受?(我知道我们可以使用慢速和快速指针来解决这个问题)
解决方案
如果您有兴趣,我已经发布了一个替代解决方案。
class Solution:
def removeNthFromEnd(self, head, n):
fast = slow = head
for _ in range(n):
fast = fast.next
if not fast:
return head.next
while fast.next:
fast = fast.next
slow = slow.next
slow.next = slow.next.next
return head
推荐阅读
- javascript - 如何使用循环在数组中求和?
- node.js - 使用和保护rabbitmq mqtt websocket并在浏览器中使用
- konvajs - 如何在 Konvajs React 中模拟像 Object-Fit Cover 这样的 CSS?
- android - Android 上 3D 安全支付的 Webview 安全性
- python - 熊猫根据条件为新列添加价值
- here-api - 如何验证我的应用程序是否可以访问 Here geocoder api?
- angular - 错误:“找不到带有路径的控件:'dispositivosForm'”
- email - 如何在 Odoo 中将关注者添加到电子邮件的收件人字段中?
- java - 我找不到获取数组中最大数的方法(Ar.getMax())。我的输出一直是 0
- node.js - 如何将 Facebook 登录脚本添加到 React?