题目;
思路:
最开始思路用递归
但后面想到要多次到头结点 就达不到 就放弃递归
然后看评论区大佬第一条 说 其实就是倒数第k个移位即可
代码:
class Solution {
ListNode pre;
ListNode tem;
int n=0;
public ListNode rotateRight(ListNode head, int k) {
if(k==0 || head==null ||head.next==null) return head;
//常规递归不行 因为要往返几次
// 将倒数第k 个作为 头
ListNode current=head;
int count=1;//链表长度
while(current.next!=null){
current = current.next;
++count;
}
if(count<=k){//3 4
k=k%count;
//k=count%k;
}
if(k==0) return head;
pre=head;
head=rotate(head,k);
return tem;
}
public ListNode rotate(ListNode head,int k){
if(head==null){
head=pre;
return head;
}
head.next=rotate(head.next,k);//head.next=null head =5
++n;
if(n==(k+1)){//n大于 链表长度时
tem=head.next;
head.next=null;
return head;
}
return head;
}
}
不用方法 直接找到倒数第n个 返回
如下
ListNode current=head;
int count=1;//链表长度
while(current.next!=null){
current = current.next;
++count;
}
if(count<=k){//3 4
k=k%count;
//k=count%k;
}
if(k==0) return head;
//ListNode start=head;
current.next=head;
for(int i=0;i<count-k;i++){
current=current.next;
}
ListNode newHead=current.next;
current.next=null;
return newHead;