给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。
进阶:你能尝试使用一趟扫描实现吗?
示例 1:
输入:head = [1,2,3,4,5], n = 2 输出:[1,2,3,5]
示例 2:
输入:head = [1], n = 1 输出:[]
示例 3:
输入:head = [1,2], n = 1 输出:[1]
一开始我的代码:
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
f = head
p = head
for i in range(n):
f = f.next
while f.next:
f = f.next
p = p.next
r = p.next
p.next = r.next
return head
跑到这一步的时候就报错文章来源:https://www.toymoban.com/news/detail-554866.html
应该给他加一个指向头节点的节点,并且返回这个节点的next,而不是返回head文章来源地址https://www.toymoban.com/news/detail-554866.html
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
dummy_head = ListNode(val=0,next=head)
f = dummy_head
p = dummy_head
for i in range(n):
f = f.next
while f.next:
f = f.next
p = p.next
r = p.next
p.next = r.next
return dummy_head.next
到了这里,关于【Leetcode】19. 删除链表的倒数第N个节点的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!