给你一个链表的头节点 head,旋转链表,将链表每个节点向右移动 k 个位置。
解题思路:
整体思路:将链表变成环,其次在合适的位置上断开连接。
- 首先遍历链表,找到链表尾节点修改其next指针,将其指向头节点,将链表连接成循环链表,同时计算链表长度。
- 再次遍历链表,在len - k % len的节点断开连接。
具体代码:
class Solution {
public ListNode rotateRight(ListNode head, int k) {
if(head == null || head.next == null || k == 0) return head;
// 1. 让链表成环
ListNode cur = head;
int len = 1;
while(cur.next != null) {
cur = cur.next;
len++;
}
cur.next = head;
// 2. 断开连接
int index = len - k % len - 1;
for(int i = 0; i < index; i++) {
head = head.next;
}
ListNode ans = head.next;
head.next = null;
return ans;
}
}
时间复杂度:O(n),最多需要遍历该链表两次。
空间复杂度:O(1),只需要常数的空间存储若干变量。