61. Rotating Linked List
Give you the head node of a linked list, rotate the linked list, and move each node of the linked list k positions to the right.
Example 1:
Input: head = [1,2,3,4,5], k = 2
Output: [4,5,1,2,3]
Example 2:
Input: head = [0,1,2], k = 4
Output: [2,0,1]
prompt:
The number of nodes in the linked list is in the range [0, 500]
-100 <= Node.val <= 100
0 <= k <= 2 * 109
/**
* 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 add = n-k%n; // 如果k>n则会重复反转
if (add == n) {
// add==n 则不需要反转
return head;
}
iter.next = head;
while (add-- > 0) {
// 反转过程
iter = iter.next;
}
ListNode ret = iter.next; // 返回的链表
iter.next = null;
return ret;
}
}