Skip to content

Instantly share code, notes, and snippets.

@dmnugent80
Last active August 29, 2015 14:16
Show Gist options
  • Save dmnugent80/0b09c6fe213959686eed to your computer and use it in GitHub Desktop.
Save dmnugent80/0b09c6fe213959686eed to your computer and use it in GitHub Desktop.
Rotate Linked List
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode rotateRight(ListNode head, int n) {
if (head == null || n == 0 || head.next == null) return head;
ListNode end = head;
int length = 1;
while (end.next != null){
end = end.next;
length++;
}
n = n%length;
if (n == 0) return head;
//make circular
end.next = head;
for (int i = 0; i < length - n; i++){
end = end.next;
}
head = end.next;
end.next = null;
return head;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment