Problem Statement
Pattern:
Solution
public ListNode rotateRight (ListNode head, int k){
// edge case
if(head == null || head.next == null) return head;
// get last pointer and length of LL
int len = 1;
ListNode last = head;
while(last.next != null) {
last = last.next;
len ++;
}
last.next = head; // point last to head
// fix k
k = k%len; // set k within bounds
k = len - k; // to rotate clockwise
// break LL and return newHead
while (--k > 0) head = head.next; // shift head to b4 breakpoint
ListNode newHead = head.next; // set newHead
head.next = null; // break LL
return newHead; // return newHead
}
Notes
Steps
- Make LL Circular
- Break at k
- return k.next as new head
Potential Issues:
- K could be much larger than LL Length
- Direction of Rotation needs to be taken into account