Last active
August 29, 2015 14:16
-
-
Save dmnugent80/0b09c6fe213959686eed to your computer and use it in GitHub Desktop.
Rotate Linked List
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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