旋转链表
题目:
思路:
先算出链表长度,然后将首位连接起来,根据K来选取K+1的位置,为新的链表的头节点。
class Solution {
public ListNode rotateRight(ListNode head, int k) {
//判断链表是否为null或者为长度为1,K是否等于0
if(head == null || head.next == null || k==0){
return head;
}
//遍历,得到链表长度
int count=1;
ListNode temp=head;
while(temp.next != null){
count++;
temp=temp.next;
}
//算出k在链表的位置
k%=count;
temp.next=head;
//找到节点temp
for(int i=0;i<count-k;i++){
temp=temp.next;
}
//建立一个新的链表,头节点为temp
ListNode newhead = temp.next;
temp.next=null;
//输出
return newhead;
}
}
把每一步也做了注释。