353. Append the Last N Nodes to Beginning

EasyLinked ListLinked ListRotationTwo Pointer

Given the head of a singly linked list and an integer n, move the last n nodes to the front. Return the new head.

If n >= length, use n = n % length. If n == 0, return unchanged.

Input: Head of a singly linked list and integer n.

Output: Head of the updated list.

Examples

Example 1
Input: [1,2,3,4,5], 2
Output: [4,5,1,2,3]
Explanation: Last 2 nodes [4,5] move to front.
Example 2
Input: [1,2,3,4,5], 0
Output: [1,2,3,4,5]
Explanation: n=0. No change.
Example 3
Input: [1,2,3,4,5], 5
Output: [1,2,3,4,5]
Explanation: n=5, n%5=0. No change.

Constraints

Asked by

TCSInfosysWiproCognizantCapgemini
Solve this problem in the editor →