列表

详情


剑指 Offer II 021. 删除链表的倒数第 n 个结点

给定一个链表,删除链表的倒数第 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]

 

提示:

 

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

 

注意:本题与主站 19 题相同: https://leetcode.cn/problems/remove-nth-node-from-end-of-list/

原站题解

去查看

上次编辑到这里,代码来自缓存 点击恢复默认模板
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* removeNthFromEnd(ListNode* head, int n) { } };

python3 解法, 执行用时: 44 ms, 内存消耗: 14.8 MB, 提交时间: 2022-11-23 16:20:16

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
        dummy = ListNode(0, head)
        first, second = head, dummy
        for i in range(n):
            first = first.next
        
        while first != None:
            second = second.next
            first = first.next
        
        second.next = second.next.next
        return dummy.next

golang 解法, 执行用时: 0 ms, 内存消耗: 2.1 MB, 提交时间: 2022-11-23 16:17:30

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func removeNthFromEnd(head *ListNode, n int) *ListNode {
    dummy := &ListNode{0, head}
    first, second := head, dummy
    for i := 0; i < n; i++ {
        first = first.Next
    }
    for ; first != nil; first = first.Next {
        second = second.Next
    }
    second.Next = second.Next.Next
    return dummy.Next

}

上一题