旋转链表
61. 旋转链表
public ListNode rotateRight(ListNode head, int k) {
if (head == null || k == 0) {
return head;
}
ListNode tmp = head;
int len = 0;
while (tmp != null) {
tmp = tmp.next;
len++;
}
k = k % len;
if (k == 0) {
return head;
}
//快慢指针
tmp = head;
ListNode node = head;
while (k > 0) {
k--;
tmp = tmp.next;
}
while (tmp.next != null) {
head = head.next;
tmp = tmp.next;
}
//记录next的位置
ListNode res = head.next;
//断开连接
head.next = null;
//后一段的末尾指向前一段的开头
tmp.next = node;
return res;
}