Skip to content

Instantly share code, notes, and snippets.

@InterviewBytes InterviewBytes/ListNode.java Secret
Created Jun 8, 2017

Embed
What would you like to do?
Rotate the list to the right by k places, where k is non-negative.
package com.interviewbytes.linkedlists;
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
package com.interviewbytes.linkedlists;
public class RotateRight {
public ListNode rotateRight(ListNode head, int k) {
if (head == null || k == 0) return head;
int count = 0;
ListNode current = head;
while (current != null) {
count++;
current = current.next;
}
if (k >= count) {
k = k % count;
}
if (k == 0) return head;
ListNode fast = head;
while (k > 0) {
fast = fast.next;
k--;
}
ListNode slow = head;
while (fast.next != null) {
slow = slow.next;
fast = fast.next;
}
ListNode newHead = slow.next;
slow.next = null;
fast.next = head;
return newHead;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.