Search⌘ K

Swap Nth Node with Head

Understand how to swap the head node with the nth node in a singly linked list. This lesson teaches you to traverse the list, identify nodes, and perform the swap with linear time and constant space complexity.

Statement

Given the head of a singly linked list and nn, swap the head with the nthn^{th} node. Return the head of the new linked list.

Example

Let’s take a look at an example where n is equal to 44.

g head head 7 7 head->7 NULL NULL 28 28 35 35 28->35 14 14 7->14 21 21 14->21 21->28 42 42 35->42 42->NULL

After swapping the Nth node with head, our ...