Rotate List

旋转链表

题目

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

解析重点

1.我们观察就可以知道旋转k个数,即将k%n个后面的数挪到前面即可。即将链表从n-k%n处分开,将后面的部分拼接到前面。
2.那么这里我们主要涉及到4个node,原来的first=node[1]、end=node[n],改变后的first1=node[n-k%n+1]、end1=node[n-k%n]。因此,我们需要计算出n->链表长度,
及end、first1、end1。然后将几个node挪动即可。

java代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode rotateRight(ListNode head, int k) {
if(head==null||head.next==null) return head;
ListNode first = head,end = head,rotate=head;
int i = 1;
for(i=1;end.next!=null;i++) end = end.next; //计算list长度n,找到end节点
for(int j=i-k%i-1;j>0;j--) rotate = rotate.next;//找到旋转节点
end.next=first;//旋转
first=rotate.next;
rotate.next=null;
return first;
}
}
undefined