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
.
Code:
/*题目大意
给出一个单链表,和一个K值,根据K值往右旋转,例如:
*/
public class LeetCode61 {
public static class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
public String toString() {
return Integer.toString(val) + " " + next;
}
}
// 324msAC----http://www.cnblogs.com/kaituorensheng/p/3647668.html
public static ListNode rotateRight(ListNode head, int k) {
if (k <= 0 || head == null) {
return head;
}
ListNode tempA = head;
int sum = 1;
while (head.next != null) {
head = head.next;
sum++;
}
System.out.println("sum: " + sum);
head.next = tempA;
head = tempA;
k = sum - k % sum;
System.out.println("k: " + k);
int i = 0;
while (i < k) {
tempA = head;
head = head.next;
i++;
}
tempA.next = null;
return head;
}
public static void main(String[] args) {
ListNode head = new ListNode(0);
ListNode a = new ListNode(1);
ListNode b = new ListNode(2);
head.next = a;
a.next = b;
b.next = null;
int k = 4;
System.out.println("rotateRight: " + rotateRight(head, k));
}
}