304. Delete a Node by Position

EasyLinked ListLinked ListDeletion

Given the head of a singly linked list and a 1-based position pos, delete the node at position pos and return the head.

Position 1 is the head. If pos > length, return the list unchanged.

Input: Head of a singly linked list and integer pos (1-based).

Output: Head of the updated linked list.

Examples

Example 1
Input: [1,2,3,4,5], 3
Output: [1,2,4,5]
Explanation: Delete node at position 3 (value=3). Node(2).next = Node(4). Return head=1.
Example 2
Input: [1,2,3,4,5], 1
Output: [2,3,4,5]
Explanation: Delete head. New head = node(2). Return node(2).
Example 3
Input: [1,2,3,4,5], 5
Output: [1,2,3,4]
Explanation: Delete last node. Node(4).next = NULL. Return head=1.

Constraints

Asked by

TCSInfosysWiproCognizantCapgemini
Solve this problem in the editor →