LeetCode hot100-29-Y

java 复制代码
19. 删除链表的倒数第 N 个结点

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

这题比较简单,我的想法和官方一是一样的,剩下的不想看了。

就是要注意一下删除的是第一个节点的情况,单独处理一下。

我的代码

java 复制代码
/**
 * Definition for singly-linked list.
 * public class ListNode {
 * int val;
 * ListNode next;
 * ListNode() {}
 * ListNode(int val) { this.val = val; }
 * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode p = head;
        ListNode pre = head;
        int num = 0;
        while (p != null) {
            num++;
            p = p.next;

        }
        p = head;
        int num2 = num - n;
        if (num2 == 0) {
            return head.next;
        }

        while (num2 > 0) {
            num2--;
            pre = p;
            p = p.next;
        }
        pre.next = p.next;
        return head;

    }
}

官方解法一

java 复制代码
class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummy = new ListNode(0, head);
        int length = getLength(head);
        ListNode cur = dummy;
        for (int i = 1; i < length - n + 1; ++i) {
            cur = cur.next;
        }
        cur.next = cur.next.next;
        ListNode ans = dummy.next;
        return ans;
    }

    public int getLength(ListNode head) {
        int length = 0;
        while (head != null) {
            ++length;
            head = head.next;
        }
        return length;
    }
}

作者:力扣官方题解
链接:https://leetcode.cn/problems/remove-nth-node-from-end-of-list/solutions/450350/shan-chu-lian-biao-de-dao-shu-di-nge-jie-dian-b-61/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
相关推荐
人间乄惊鸿客6 小时前
c++ 右值
c++·算法
fanstuck7 小时前
AI 客服答错了,三分钟分清是 Prompt 还是系统的锅
算法
田里的水稻8 小时前
FA_编程算法200个分类列数-SUM
算法·分类·数据挖掘
猿人谷10 小时前
从百万个 Pareto 解中选出 100 个:Riesz s-Energy 如何实现高效的多样性选择?
后端·算法·aigc
地平线开发者10 小时前
地平线 × 同济无人车队:PointPillars 从浮点模型到 BPU 部署
算法·自动驾驶
iiiiii1111 小时前
从最大熵到 SAC:Soft Q-Learning 与 Soft Actor-Critic 公式推导笔记
人工智能·笔记·算法·机器学习·强化学习
田里的水稻12 小时前
FA_排序算法-冒泡排序
java·算法·排序算法
AAA修煤气灶刘哥14 小时前
AI 写的 SQL 跑通了,为什么和财务报表对不上?
人工智能·后端·算法