题目描述:
给你一个链表的头节点 head ,旋转链表,将链表每个节点向右移动 k 个位置。
一、基础类
public static 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;
Queue<ListNode> tmp = new LinkedList<>();
while (head.next != null) {
tmp.offer(head);
head = head.next;
}
ListNode tail = head;
tmp.offer(head);
int len = tmp.size();
k %= len;
k = len - k;
for (int i = 0; i < k; ++i) {
ListNode cur = tmp.poll();
cur.next = null;
tail.next = cur;
tmp.offer(cur);
tail = cur;
}
return tmp.poll();
}
}
排行
- 执行耗时:1 ms,击败了39.14% 的Java用户
- 内存消耗:38 MB,击败了11.34% 的Java用户
三、官方解答
思路
可以先将给定的链表连接成环,然后将指定位置断开。
代码
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;
}
}
复杂度分析
- 时间复杂度:O(n),最坏情况下,我们需要遍历该链表两次。
- 空间复杂度:O(1),我们只需要常数的空间存储若干变量。
排行
- 执行耗时:0 ms,击败了100.00% 的Java用户
- 内存消耗:37.8 MB,击败了53.63% 的Java用户