[Leetcode 19]Remove Nth Node From End of List

Description:

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

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

C code solution 1:

/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/

Explanation:

先確認linked list長度,再將長度減掉n來確定走到target remove node的前一個node需要幾步,再走到那個node,最後進行node removal。

C code solution 2:

/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/

Explanation:

利用三個指標 prev ptr nstepsprev 指到remove target的前一個node,ptr 指到remove target,nsteps 會指到tail。一開始先將ptr nsteps 這兩個取好n的距離,接著讓nsteps 帶著其他pointer走直到tail,這樣以來ptr 就會剛好指向要被remove target。

Hi I am Samuel