317. Move Last Node to Front

EasyLinked ListLinked ListPointer Manipulation

Given the head of a singly linked list, move the last node to the front and return the new head.

Traverse to the second-to-last node, unlink the last, and prepend it to the front.

Input: Head of a singly linked list.

Output: Head of the updated list with the last node at the front.

Examples

Example 1
Input: [1,2,3,4,5]
Output: [5,1,2,3,4]
Explanation: Traverse to node(4). Unlink node(5). newHead=node(5), node(5).next=node(1). Return node(5).
Example 2
Input: [10,20,30]
Output: [30,10,20]
Explanation: Unlink node(30) from node(20). Prepend node(30). Result: 30→10→20.
Example 3
Input: [7]
Output: [7]
Explanation: Single node. No change needed.

Constraints

Asked by

TCSInfosysWiproCognizantCapgemini
Solve this problem in the editor →