class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
# leetcode submit region end(Prohibit modification and deletion)
tmp, tmp.next = ListNode(None), head
pre = cur = tmp
while n:
cur = cur.next
n -= 1
while cur.next:
cur = cur.next
pre = pre.next
pre.next = pre.next.next
return tmp.next
之前错误的代码
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
# leetcode submit region end(Prohibit modification and deletion)
if head.next is None:
return None
pre = cur = head
tmp = n
while n:
cur = cur.next
n -= 1
while cur.next:
cur = cur.next
pre = pre.next
pre.next = cur # 注意这一点错了,调了好长时间,这个是直接将中间的隔过去
if tmp == 1:
pre.next = None
return head
链表题技巧
- 加一个头节点 操作,返回头节点的next
- 要删除某个节点,就得知他前面的节点或者是它自身的指针。cur = cur.next
- 经常需要两个指针:或者同步指针,或者快慢指针
本文介绍了一种有效的算法,用于在链表中删除倒数第N个节点。通过使用双指针技巧,文章详细解释了如何在一次遍历中找到目标节点并进行删除操作。此外,还分享了链表题目的常见技巧和注意事项。
6272

被折叠的 条评论
为什么被折叠?



