/**
* 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) return head;
//获取链表长度
ListNode tmp = head;
int len = 0;
while (tmp != null) {
tmp = tmp.next;
len++;
}
//如果k是len的整数倍,说明无须移动
if (k % len == 0) return head;
//链表分为A-B段,A段为 len - k % len B段为 k % len
int aLen = len - k % len;
int bLen = k % len - 1;
ListNode nodeA = head, nodeB = new ListNode(-1);
while (aLen-- > 1) {
nodeA = nodeA.next;
}
//将A-B断开
nodeB.next = nodeA.next;
nodeA.next = null;
//将B-A组装上
tmp = nodeB.next;
while(bLen-- > 0) {
tmp = tmp.next;
}
tmp.next = head;
return nodeB.next;
}
}
复杂度分析:
- 时间复杂度:O(n)
- 空间复杂度:O(1)