Skip to content

Commit

Permalink
Rotate List
Browse files Browse the repository at this point in the history
  • Loading branch information
mengli committed Jan 7, 2014
1 parent c00c4cf commit 13ce25b
Showing 1 changed file with 36 additions and 0 deletions.
36 changes: 36 additions & 0 deletions RotateList.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/**
* 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 RotateList {
public ListNode rotateRight(ListNode head, int n) {
if (head == null)
return head;
int length = 1;
ListNode last = head;
while (last.next != null) {
last = last.next;
length++;
}
n = n % length;
if (n == 0)
return head;
int steps = length - n;
ListNode start = new ListNode(0);
start.next = head;
while (steps > 0) {
start = start.next;
steps--;
}
ListNode ret = start.next;
start.next = null;
last.next = head;
return ret;
}
}

0 comments on commit 13ce25b

Please sign in to comment.