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
.
首先计算链表长度,将链表首尾相接,之后得出链表从head开始起的正向偏移量,从head开始遍历找到旋转后的head,再“扯断”成环的链表,返回新的head.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode rotateRight(ListNode head, int n) {
ListNode p=head;
if(head==null || n==0)return head;
int len=1;
while(p.next!=null)
{
p=p.next;
len++;
}
p.next=head;
n=len-n%len;
while(n>0)
{
p=p.next;
n--;
}
head=p.next;
p.next=null;
return head;
}
}