题意
给你一个链表的头节点 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]
提示:
链表中节点的数目在范围 [0, 500] 内
-100 <= Node.val <= 100
0 <= k <= 2 * 109
解题思路
我们将单向链表变为循环链表,之后只要找到断点断开即可
代码演示
class Solution {
public ListNode rotateRight(ListNode head, int k) {
if(head==null)
return head;
int num=1;
ListNode end=head;
while (end.next!=null)
{
num++;
end=end.next;
}
end.next=head;
int pre=num-k%num;
num=0;
while (num!=pre-1)
{
head=head.next;
num++;
}
ListNode res=head.next;
head.next=null;
return res;
}
}
效果演示
info
解答成功:
执行耗时:1 ms,击败了51.22% 的Java用户
内存消耗:37.9 MB,击败了36.97% 的Java用户