给你一个链表的头节点 head
,旋转链表,将链表每个节点向右移动 k
个位置。
例如:
输入:head = [1,2,3,4,5], k = 2 输出:[4,5,1,2,3]
题解:
记给定链表的长度为 n,注意到当向右移动的次数 k≥n 时,我们仅需要向右移动 k mod n 次即可。因为每 n次移动都会让链表变为原状。这样我们可以知道,新链表的最后一个节点为原链表的第 (n−1)−(k mod n)个节点(从 0 开始计数)。
/**
* 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;
if (add ==n){
return head;
}
iter.next =head;
while (add -- >0){
iter =iter.next;
}
ListNode ret =iter.next;
iter.next =null;
return ret;
}
}