给你一个链表的头节点
head
,旋转链表,将链表每个节点向右移动k
个位置。示例1:
输入:head = [1,2,3,4,5], k = 2 输出:[4,5,1,2,3]示例2:
输入:head = [0,1,2], k = 4 输出:[2,0,1]
public ListNode rotateRight(ListNode head, int k) {if(head == null || k == 0){return head;}int count = 1;ListNode cur = head;while(cur.next != null){count++;cur = cur.next;}ListNode tail = cur;k = k % count;//找出第n - k 个节点cur = head;for(int i = 0; i < count - k - 1;i++){cur = cur.next;}tail.next = head;head = cur.next;cur.next = null;return head;}