题目
给你一个链表的头节点 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
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/rotate-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
1.遍历一次找到尾节点,把它接到头节点上,变成循环链表
2.右移一位后,头节点就是尾节点,俩位就是倒二个节点,所以,我们直接用头节点一直右移链表长度n-k的长度,得到的就是右移后的头节点,然后再把循环链表的尾节点置为null。
代码
/**
* 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(head==null){
return head;
}
ListNode last=head;
int length=1;
while(last.next!=null){
last=last.next;
length++;
}
last.next=head;
ListNode first=head;
if(k>length)
k=k%length;
for(int i=0;i<length-k;i++){
first=first.next;
last=last.next;
}
last.next=null;
return first;
}
}