1. 程式人生 > 其它 >leetcode 19.刪除連結串列的倒數第N個節點 Java

leetcode 19.刪除連結串列的倒數第N個節點 Java

技術標籤:leetcode刷題leetcode連結串列

刪除連結串列的倒數第N個節點

做題部落格連結

https://blog.csdn.net/qq_43349112/article/details/108542248

題目連結

https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/

描述

給你一個連結串列,刪除連結串列的倒數第 n 個結點,並且返回連結串列的頭結點。

進階:你能嘗試使用一趟掃描實現嗎?

提示:

連結串列中結點的數目為 sz
1 <= sz <=
30 0 <= Node.val <= 100 1 <= n <= sz

示例

示例 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.
 * 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) { } }

程式碼

/**
 * 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 prevHead = new ListNode(-1); prevHead.next = head; ListNode fast = prevHead; ListNode slow = prevHead; for (int i = 0; i < n; i++) { fast = fast.next; } while (fast.next != null) { fast = fast.next; slow = slow.next; } slow.next = slow.next.next; return prevHead.next; } }