把倒数k个节点放到开始节点的前面,注意 n可能很大,需要对长度取余。
/**
* 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) {
if(head == null || head.next == null)return head;
int count = 0;
int cur = 0;
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode p = head;
ListNode pre = head;
while(p != null){
count++;
p = p.next;
}
n = n % count;
if(n == 0) return head;
p = head;
while(p != null){
cur++;
pre = p;
p = p.next;
if(cur == count - n) break;
}
pre.next = null;
ListNode newHead = p;
while(p != null){
pre = p;
p = p.next;
}
pre.next = dummy.next;
return newHead;
}
}