1. 程式人生 > 其它 >LeetCode刷題記錄:19. 刪除連結串列的倒數第 N 個結點-Remove Nth Node From End of List

LeetCode刷題記錄:19. 刪除連結串列的倒數第 N 個結點-Remove Nth Node From End of List

技術標籤:# LeetCode Java題解集連結串列javaleetcode

LeetCode刷題記錄:19. 刪除連結串列的倒數第 N 個結點-Remove Nth Node From End of List

題目

給你一個連結串列,刪除連結串列的倒數第 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]

提示

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

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

解題思路

頭結點存在被刪除的情況需要單獨判斷。雙指標間隔為n,當尾指標到尾端時,頭指標即指向倒數第n個節點。

java實現

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution { public ListNode removeNthFromEnd(ListNode head, int n) { ListNode pre = new ListNode(0); pre.next = head; ListNode start = head; ListNode end = head; while (n > 0) { end = end.next; n--; } if (end ==
null) { pre.next = pre.next.next; } else { while (end.next != null) { start = start.next; end = end.next; } start.next = start.next.next; } return pre.next; } }

執行用時:0 ms, 在所有 Java 提交中擊敗了100.00%的使用者
記憶體消耗:36.4 MB, 在所有 Java 提交中擊敗了54.43%的使用者