题目

思路
- 没什么好说的,刚开始没发现头结点是倒数第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;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33