Published on

# Rearrange Last N

Authors

## Problem

Note: Try to solve this task in `O(list size)` time using `O(1)` additional space, since this is what you'll be asked during an interview.

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]` and `n = 3`, the output should be
`solution(l, n) = [3, 4, 5, 1, 2]`;
• For `l = [1, 2, 3, 4, 5, 6, 7]` and `n = 1`, the output should be
`solution(l, n) = [7, 1, 2, 3, 4, 5, 6]`.

## Solution

`_38// Singly-linked lists are already defined with this interface:_38// type ListNode struct {_38// Value interface{}_38// Next *ListNode_38// }_38//_38func solution(l *ListNode, n int) *ListNode {_38 if l == nil || l.Next == nil || n == 0 {_38 return l_38 }_38_38 // Count the length of the list_38 length := 1_38 lastNode := l_38 for lastNode.Next != nil {_38 length++_38 lastNode = lastNode.Next_38 }_38_38 // Handle edge cases_38 n = n % length_38 if n == 0 {_38 return l_38 }_38_38 // Find the new head and tail of the list_38 newTail := l_38 for i := 1; i < length-n; i++ {_38 newTail = newTail.Next_38 }_38 newHead := newTail.Next_38_38 // Update pointers_38 lastNode.Next = l_38 newTail.Next = nil_38_38 return newHead_38}`