【Leetcode】19. 删除链表的倒数第N个节点

给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。

进阶:你能尝试使用一趟扫描实现吗?

示例 1:

【Leetcode】19. 删除链表的倒数第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

跑到这一步的时候就报错

应该给他加一个指向头节点的节点,并且返回这个节点的next,而不是返回head

# 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,leetcode,链表,算法)