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)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
相关推荐
数研小生9 小时前
构建命令行单词记忆工具:JSON 词库与艾宾浩斯复习算法的完美结合
算法·json
芒克芒克9 小时前
LeetCode 题解:除自身以外数组的乘积
算法·leetcode
Python 老手9 小时前
Python while 循环 极简核心讲解
java·python·算法
@Aurora.9 小时前
优选算法【专题九:哈希表】
算法·哈希算法·散列表
爱看科技10 小时前
微美全息(NASDAQ:WIMI)研究拜占庭容错联邦学习算法,数据安全与隐私保护的双重保障
算法
qq_4171292510 小时前
C++中的桥接模式变体
开发语言·c++·算法
YuTaoShao10 小时前
【LeetCode 每日一题】3010. 将数组分成最小总代价的子数组 I——(解法二)排序
算法·leetcode·排序算法
XH华12 小时前
备战蓝桥杯,第七章:函数与递归
职场和发展·蓝桥杯
吴维炜12 小时前
「Python算法」计费引擎系统SKILL.md
python·算法·agent·skill.md·vb coding
Σίσυφος190013 小时前
PCL Point-to-Point ICP详解
人工智能·算法