Problem: 61. 旋转链表
👨🏫 力扣官解
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode rotateRight(ListNode head, int k) {
// 不用动 或 链表少于两个节点
if(k == 0 || head == null || head.next == null){
return head;
}
int n = 1;// 统计链表的元素个数
ListNode iter = head;
while(iter.next != null){
iter = iter.next;
n++;
}
int offset = n - (k % n);// 从头开始数 offset 个,链表断开
if(offset == n){
return head;
}
iter.next = head;// 闭链成环
// 把 iter 移到第 offset 个节点
while(offset-- > 0){
iter = iter.next;
}
ListNode res = iter.next;
iter.next = null;// 断环归链
return res;
}
}