תיאור השאלה
Given the head of a linked list, rotate the list to the right by k places.
איך פותרים?
Turn the list into a cycle, then break it after `length - (k % length)` nodes to rotate.
פתרון קוד
JavaScript
Python
function rotateRight(head, k) {
if (!head || !head.next || k === 0) {
return head;
}
let tail = head;
let length = 1;
while (tail.next) {
tail = tail.next;
length++;
}
k %= length;
if (k === 0) {
return head;
}
tail.next = head;
let stepsToNewTail = length - k - 1;
let newTail = head;
while (stepsToNewTail--) {
newTail = newTail.next;
}
const newHead = newTail.next;
newTail.next = null;
return newHead;
}הסבר וידאו כיצד לפתור את השאלה

לעבור את ראיון העבודה הבא שלך בהצלחה
קורס דיגיטלי מקיף עם +25 שיעורים מעשיים, כשעתיים של וידאו, וליווי של מראיין בכיר.