Skip to content

Instantly share code, notes, and snippets.

@fever324
Last active August 29, 2015 14:09
Show Gist options
  • Save fever324/3182c6665365b3cb2a5a to your computer and use it in GitHub Desktop.
Save fever324/3182c6665365b3cb2a5a to your computer and use it in GitHub Desktop.
Rotate List
/*
* Given a list, rotate the list to the right by k places, where k is non-negative.
*
* For example:
* Given 1->2->3->4->5->NULL and k = 2,
* return 4->5->1->2->3->NULL.
*/
public class Solution {
public ListNode rotateRight(ListNode head, int n) {
// make sure list length > 1
if (head == null || n == 0 || head.next == null) {
return head;
}
ListNode end = head;
int size = 1;
while (end.next != null) {
end = end.next;
size ++;
}
n = n % size;
if(n == 0) {
return head;
}
ListNode connection = head;
for(int i = 0 ; i< size - n -1; i++) {
connection = connection.next;
}
end.next = head;
head = connection.next;
connection.next = null;
return head;
}
}
// Definition for singly-linked list.
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment