Last active
August 29, 2015 14:09
-
-
Save fever324/3182c6665365b3cb2a5a to your computer and use it in GitHub Desktop.
Rotate List
This file contains 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
/* | |
* 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