Skip to content

Instantly share code, notes, and snippets.

@wszdwp
Created November 8, 2014 17:53
Show Gist options
  • Select an option

  • Save wszdwp/de6022d09f9614487278 to your computer and use it in GitHub Desktop.

Select an option

Save wszdwp/de6022d09f9614487278 to your computer and use it in GitHub Desktop.
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.
/**
* 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) {
//http://fisherlei.blogspot.com/2013/01/leetcode-rotate-list.html
if (n == 0 || head == null)
return head;
int len = 1;
ListNode p = head;
while (p.next != null) {
p = p.next;
len++;
}
if (n == len)
return head;
n = len - n % len;
p.next = head;
int step = 0;
while (step < n) {
p = p.next;
step++;
}
head = p.next;
p.next = null;
return head;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment