题干
示例 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
示例 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
想法
看题干我们就知道了
肯定是先定位到链表尾巴构成循环链表
再通过k值决定新断开的位置
直接看代码
Java代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
/**
* 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(k==0)
return head;
if(head==null)
return head;
int length=1;
ListNode cur=head;
while(cur.next!=null)
{
cur=cur.next;
length++;
}
cur.next=head;//已经把链表首尾相接的连上了
int m=length-k%length;//这个是算法的关键,找到应该在何处断开
for(int i=0;i<m;i++)
{
cur=cur.next;
}
ListNode newhead=cur.next;//获得新的链表头节点
cur.next=null;//断开链表环
return newhead;
}
}