Problem Statement: 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.
Examples: For l = [1, 2, 3, 4, 5]
and n = 3
, the output should besolution(l, n) = [3, 4, 5, 1, 2]
;
For l = [1, 2, 3, 4, 5, 6, 7]
and n = 1
, the output should besolution(l, n) = [7, 1, 2, 3, 4, 5, 6]
.
// Singly-linked lists are already defined with this interface:
// class ListNode<T> {
// ListNode(T x) {
// value = x;
// }
// T value;
// ListNode<T> next;
// }
//
ListNode<Integer> solution(ListNode<Integer> head, int n) {
if(head==null || head.next==null || n==0)
return head;
ListNode<Integer> temp = head;
int count = 0;
// count the number of nodes in the list
while(temp!=null) {
count++;
temp = temp.next;
}
int i = 0;
temp = head;
// go till the nth node from last
while(i!=count-n) {
temp = temp.next;
i++;
}
// make this node head of the new list
ListNode<Integer> newhead = temp;
// keep traversing until reach just before the end of the list
while(temp.next!=null) {
temp = temp.next;
}
// set the next of the last node to first node in the original list
temp.next = head;
// Now keep traversing the original list until reached to the new head
ListNode<Integer> tempstart = head;
while(tempstart.next!=newhead) {
tempstart = tempstart.next;
}
// set the next of node just before new head to null
tempstart.next = null;
return newhead;
}
Time Complexity - O(listlength)
Space Complexity - O(1)