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
//
_38
func 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
}