First, the subject description:
Given a list, the list of rotation, each of the node list to the right by k positions, wherein k is non-negative.
Example 1:
输入: 1->2->3->4->5->NULL, k = 2
输出: 4->5->1->2->3->NULL
解释:
向右旋转 1 步: 5->1->2->3->4->NULL
向右旋转 2 步: 4->5->1->2->3->NULL
Example 2:
输入: 0->1->2->NULL, k = 4
输出: 2->0->1->NULL
解释:
向右旋转 1 步: 2->0->1->NULL
向右旋转 2 步: 1->2->0->NULL
向右旋转 3 步: 0->1->2->NULL
向右旋转 4 步: 2->0->1->NULL
Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/rotate-list
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.
Second, the problem-solving ideas:
Chain length is obtained, the list even form a ring, walking (size-k% size-1) step by a tail node of the new list, the ring can be turned off.
note:
Each node list will move to the right k places, even after the list is equivalent to form a ring, k penultimate node for the first node to the new list, OFF penultimate nodes k + 1 (new tail node linked list) , just go size- (k + 1) step; when k> when the size, take the (size-k% size-1) step.
Third, Code Description:
/**
* 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||k==0){
return head;
}
int size=getSize(head);
ListNode newHead=null;
ListNode cur=head;
//将链表连成环,遍历链表,用链表最后一个节点的next指向head
while(cur.next!=null){
cur=cur.next;
}
cur.next=head;
//找到旋转后新链表的尾节点,使尾节点的next指向null
int steps=size-k%size-1;
for(int i=0;i<steps;i++){
head=head.next;
}
//for循环结束后,head指向旋转后新链表的尾节点。
newHead=head.next;
head.next=null;
return newHead;
}
//获取链表长度
private int getSize(ListNode head){
int size=0;
for(ListNode cur=head;cur!=null;cur=cur.next){
size++;
}
return size;
}
}