Problem 205810 · medium · Level 02 Linear Data Structures

Uncouple a Wagon Counted From the Back

linked list · two pointers · deletion

A goods train is a singly linked list of wagons, engine end first. The shunter must take out the n-th wagon counting from the back (n = 1 is the last wagon) and couple the rest together again. Given the head and n, return the head of the shortened train (which may be empty).

Examples

Input:  head = 4 -> 9 -> 6 -> 2 -> 7 -> 5, n = 3
Output: 4 -> 9 -> 6 -> 7 -> 5

Input:  head = 9, n = 1
Output: (empty)

Constraints

  • 1 <= number of nodes <= 10**4
  • 1 <= n <= number of nodes
  • Target: O(n) time, O(1) extra space, in one pass (no counting pass first)

Goals

  • Place a trailing pointer exactly before the node to delete
  • Delete the head with the same code path as any other node
Starting Python…