Skip to content

Instantly share code, notes, and snippets.

@cxtadment
Created September 2, 2015 17:44
Show Gist options
  • Select an option

  • Save cxtadment/6bb93514c6865a591f72 to your computer and use it in GitHub Desktop.

Select an option

Save cxtadment/6bb93514c6865a591f72 to your computer and use it in GitHub Desktop.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
/**
* @param head: the List
* @param k: rotate to the right k places
* @return: the list after rotation
*/
public ListNode rotateRight(ListNode head, int k) {
// write your code here
if (head == null || k == 0) {
return head;
}
int length = getLength(head);
ListNode newHead = null;
ListNode preMarkHead = head;
k = k % length;
if (k == 0) {
return head;
}
for (int i = 1; i < length - k; i++) {
head = head.next;
}
newHead = head.next;
ListNode reverseHead = head.next;
head.next = null;
while (reverseHead.next != null) {
reverseHead = reverseHead.next;
}
reverseHead.next = preMarkHead;
return newHead;
}
private int getLength(ListNode head) {
int size = 0;
while (head != null) {
size++;
head = head.next;
}
return size;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment