一.题目描述
给你一个链表的头节点 head
,旋转链表,将链表每个节点向右移动 k
个位置。
https://leetcode-cn.com/problems/rotate-list/
二.代码
public ListNode rotateRight(ListNode head, int k) {
if (head == null || k == 0) {
return head;
}
ListNode cur = head;
ListNode tail;
int length = 1;
while (cur.next != null) {
cur = cur.next;
length++;
}
int loop = length - (k % length);
tail = cur;
tail.next = head;
cur = head;
for (int i = 0; i < loop; i++) {
cur = cur.next;
tail = tail.next;
}
tail.next = null;
return cur;
}