RearrangeLastN
Given a singly linked list of integers l
and a non-negative integer n
, move the last n
list nodes to the beginning of the linked list.
Example
For
l = [1, 2, 3, 4, 5]
andn = 3
, the output should besolution(l, n) = [3, 4, 5, 1, 2]
;For
l = [1, 2, 3, 4, 5, 6, 7]
andn = 1
, the output should besolution(l, n) = [7, 1, 2, 3, 4, 5, 6]
.
Idea
Check if n is 0 or greater than length of list, if so, cannot rearrange
Get length of list and iterate first half from 0 to (length-n), store in head
Get second half from length-n to end, store as newHead
newHead.next = head
Code
Last updated