美文网首页
leetcode 19 - 删除链表的倒数第 N 个结点

leetcode 19 - 删除链表的倒数第 N 个结点

作者: 那钱有着落吗 | 来源:发表于2021-08-26 16:55 被阅读0次

作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/solution/shan-chu-lian-biao-de-dao-shu-di-nge-jie-dian-b-61/
来源:力扣(LeetCode)

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

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

 

示例 1:

image.png
输入:head = [1,2,3,4,5], n = 2
输出:[1,2,3,5]
示例 2:

输入:head = [1], n = 1
输出:[]
示例 3:

输入:head = [1,2], n = 1
输出:[1]
 

提示:

链表中结点的数目为 sz
1 <= sz <= 30
0 <= Node.val <= 100
1 <= n <= sz

思路:

其实这道题的难度还是比较简单,我们想要去掉倒数第N个结点,那么必然首先得找到这个节点,然后前一个节点的指针指向这个节点的下一个即可,所以首先你得知道链表长度,然后就可以知道倒数N个结点位置就是 length-n+1。

答案

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;
    }
}

相关文章

网友评论

      本文标题:leetcode 19 - 删除链表的倒数第 N 个结点

      本文链接:https://www.haomeiwen.com/subject/jtyuiltx.html