1. 程式人生 > 其它 >LeetCode T19 Remove Nth Node From End of List

LeetCode T19 Remove Nth Node From End of List

技術標籤:LeetCode-300leetcode

題目地址:

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

題目描述:

Given the head of a linked list, remove the nth node from the end of the list and return its head.

Follow up: Could you do this in one pass?

Example 1:
在這裡插入圖片描述

Input: head = [1,2,3,4,5], n = 2
Output: [1,2,3,5]

Example 2:

Input: head = [1], n = 1
Output: []

Example 3:

Input: head = [1,2], n = 1
Output: [1]

Constraints:

The number of nodes in the list is sz.
1 <= sz <= 30
0 <= Node.val <= 100
1 <= n <= sz

思路:

本題目要將倒數第n個結點從連結串列中刪除,然後返回頭結點。

如果先遍歷一遍確定數量的話,這樣需要遍歷兩遍。
可以設定雙指標,間隔n,這樣當後一個指向尾結點的時候,前一個指標就指向倒數第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 res = new ListNode(0); res.next = head; ListNode first = res; ListNode second = res; //把後邊的指標往後挪 for(int i=0;i<n;i++){ second = second.next; } while (second.next!=null){ first = first.next; second = second.next; } first.next = first.next.next; return res.next; } }