题目:
Given a linked list, rotate the list to the right by k places, where k is non-negative.
Example 1:
Input: 1->2->3->4->5->NULL, k = 2
Output: 4->5->1->2->3->NULL
Explanation:
rotate 1 steps to the right: 5->1->2->3->4->NULL
rotate 2 steps to the right: 4->5->1->2->3->NULL
Example 2:
Input: 0->1->2->NULL, k = 4 Output:2->0->1->NULL
Explanation: rotate 1 steps to the right: 2->0->1->NULL rotate 2 steps to the right: 1->2->0->NULL rotate 3 steps to the right:0->1->2->NULL
rotate 4 steps to the right:2->0->1->NULL
题解:
这道题主要先理解题意,就是倒着数k个node,从那开始到结尾和之前那部分对调,那个例子就是,4->5拿前面来,1->2->3拿后面去。
几个特殊:
k是可以大于整个list的长度的,所以这时要对k对len取模
如果取模之后得0,相当于不用rotate,直接返回
处理完特殊情况后,把整个list连起来,变成环,找到切分点断开就行。
代码:
public class RotateList {
public static void main(String[] args) {
/**
* Given a linked list, rotate the list to the right by k places, where k is
* non-negative.
*
* Example 1:
*
* Input: 1->2->3->4->5->NULL, k = 2 Output: 4->5->1->2->3->NULL Explanation:
* rotate 1 steps to the right: 5->1->2->3->4->NULL rotate 2 steps to the right:
* 4->5->1->2->3->NULL Example 2:
*
* Input: 0->1->2->NULL, k = 4 Output: 2->0->1->NULL Explanation: rotate 1 steps
* to the right: 2->0->1->NULL rotate 2 steps to the right: 1->2->0->NULL rotate
* 3 steps to the right: 0->1->2->NULL rotate 4 steps to the right:
* 2->0->1->NULL
*/
ListNode ln11 = new ListNode(1);
ListNode ln12 = new ListNode(2);
ListNode ln13 = new ListNode(3);
ListNode ln14 = new ListNode(4);
ListNode ln15 = new ListNode(5);
ln11.next = ln12;
ln12.next = ln13;
ln13.next = ln14;
ln14.next = ln15;
LeetCodeUtil.printNodeList(rotateRight(ln11, 2));
ListNode ln20 = new ListNode(0);
ListNode ln21 = new ListNode(1);
ListNode ln22 = new ListNode(2);
ln20.next = ln21;
ln21.next = ln22;
LeetCodeUtil.printNodeList(rotateRight(ln20, 4));
}
public static ListNode rotateRight(ListNode head, int k) {
if (head == null || head.next == null) {
return head;
}
ListNode p = head;
int len = 1;// since p is already point to head
while (p.next != null) {
len++;
p = p.next;
}
p.next = head; // form a loop
k = k % len;
if (k == 0) {
return head;
}
for (int i = 0; i < len - k; i++) {
p = p.next;
} // now p points to the prev of the new head
head = p.next;
p.next = null;
return head;
}
}