61. 旋转链表
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode rotateRight(ListNode head, int k) {
if (head == null) {
return head;
}
// 统计链表长度并对k进行取余操作
int length = 1;
ListNode tmp = head;
while (tmp.next != null) {
tmp = tmp.next;
++length;
}
k = k % length;
if (k == 0) {
return head;
}
// 寻找倒数第k+1个节点
ListNode p1 = head, p2 = head;
for (int i = 0; i < k; ++i) {
p2 = p2.next;
}
while (p2.next != null) {
p1 = p1.next;
p2 = p2.next;
}
// 旋转链表
ListNode newHead = p1.next;
p1.next = null;
p2.next = head;
return newHead;
}
}