题目
思路
- 没什么好说的,刚开始没发现头结点是倒数第k个结点,还以为是k+1个结点,折腾了半天,发现了就好了。
代码
public ListNode rotateRight(ListNode head, int k) {
if(head==null) return null;
if(k==0) return head;
int length = 0;
ListNode fast = head;
ListNode slow = head;
while (fast!=null){
length++;
fast = fast.next;
}
k = k % length;
fast = head;
for(int i=0;i<k;i++) fast = fast.next;
ListNode pre = head;
while (fast!=null){
fast = fast.next;
pre = slow;
slow = slow.next;
}
if(slow == null){
return head;
}
pre.next=null;
ListNode new_head = new ListNode(0);
new_head.next = slow;
while (slow.next!=null) slow = slow.next;
slow.next=head;
return new_head.next;
}