var rotateRight = function(head, k) {
if(head === null || head.next === null){
return head;
}
for(let i=0; i<k; i++){
let current = head;
let previous = head;
while (current?.next){
previous = current;
current = current.next;
}
let lastElement = previous.next;
previous.next = null;
lastElement.next = head;
head=lastElement
}
return head;
};
let current = head;
let slow = head;
let fast = head;
let size = 0;
if(!head || !head.next) return head;
while(current) {
current = current.next;
size++;
}
let shiftBy = k % size;
if (shiftBy === 0) return head;
while(shiftBy--) {
fast = fast.next;
}
while(fast.next) {
fast = fast.next;
slow = slow.next;
}
fast.next = head;
head = slow.next;
slow.next = null;
return head;
Top comments (0)