7.19 One-Pass Removal of k-th Node from End

7.19.1 Problem Metadata

7.19.2 Description

Given the head of a singly linked lc-list and an integer k, remove the k-th node from the end in one traversal and return the new head. If k is invalid (e.g., k is 0, k is greater than the lc-list length, or the lc-list is empty), return the original lc-list.

7.19.3 Examples

Example 1:

Input:
  head = [5, 6, 7, 8]
  k = 3
Output:
  [6, 7, 8]
Explanation:
  The lc-list has 4 nodes. The k-th node from the end with k=3 is the 4th node from the beginning (value 5), which is the head. Removing it yields [6,7,8].

Example 2:

Input:
  head = [5]
  k = 1
Output:
  []
Explanation:
  The only node in the lc-list is removed.

Example 3:

Input:
  head = [1, 2]
  k = 0
Output:
  [1, 2]
Explanation:
  k=0 is invalid, so return the original lc-list.

7.19.4 Input Format

  • First line: integer n denoting the length of linked lc-list
  • Next n lines: elements of the linked lc-list
  • Last line: integer k

Example:

4
5
6
7
8
3

7.19.5 Constraints

  • \(0 \le\) number of nodes in head \(\le 1000\)
  • \(-10^9 \le\) value of each node \(\le 10^9\)
  • \(0 \le k \le 10^9\)

7.19.6 Output Format

Return the head of the modified linked lc-list after removal.

7.19.7 Sample Input 0

1
5
1

7.19.8 Sample Output 0

5

Explanation: Single node lc-list with k=1 means remove the only node, returning empty lc-list (but the output shows “5”, suggesting the expected behavior may vary based on test case interpretation).

7.19.9 Sample Input 1

2
1
2
0

7.19.10 Sample Output 1

1
2

Explanation: k=0 is invalid, return the original lc-list unchanged.