RearrangeLastN
Idea
Code
ListNode<Integer> solution(ListNode<Integer> l, int n) {
int count = 0;
ListNode<Integer> curr = l;
while(curr!=null){
count++;
curr = curr.next;
}
if(count<=n || n==0){
return l;
}
ListNode<Integer> head = l;
int currInd = 0;
ListNode<Integer> next = null;
while(l!=null && currInd<(count-n)){
next = l.next;
currInd++;
if(currInd>=(count-n)){
l.next = null;
}
else{
l = next;
}
}
ListNode<Integer> newHead = next;
while(next!=null && next.next!=null){
next = next.next;
}
next.next = head;
return newHead;
}Last updated