阅读设置
界面、侧栏和正文分别调整,自动保存。
主题切换
界面、侧栏和正文分别调整,自动保存。
问题描述: 给定一个链表的头节点 head,将链表每个节点向右移动 k 个位置。
示例:
输入:
head = [1,2,3,4,5],k = 2输出:[4,5,1,2,3]
n,右移 k 位等价于右移 k % n 位;n,计算实际旋转步数 k = k % n;n-k 个节点),其下一个节点即为新头;package lc0_lc99.lc61;
class Solution {
public ListNode rotateRight(ListNode head, int k) {
if (head == null) {
return head;
}
int n = 0;
ListNode count = head;
while (count.next != null) {
count = count.next;
n++;
}
n++;
if (n == 1) {
return head;
}
k = k % n;
if (k == 0) {
return head;
}
int headNum = n - k;
int tailNum = n - k - 1;
ListNode tail;
ListNode oldHead = head;
for (int i = 0; i < tailNum; i++) {
head = head.next;
}
tail = head;
head = tail.next;
tail.next = null;
ListNode last = head;
while (last.next != null) {
last = last.next;
}
last.next = oldHead;
return head;
}
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 null;
// 统计链表长度
int size = 0;
ListNode p = head, tail = null;
while (p != null) {
size++;
tail = p;
p = p.next;
}
// 计算实际旋转步数
k %= size;
if (k == 0) return head;
// 找到新的尾节点(第 size - k 个节点)
ListNode newTail = head;
for (int i = 1; i < size - k; i++) {
newTail = newTail.next;
}
// 断尾、接原头
ListNode newHead = newTail.next;
newTail.next = null;
tail.next = head;
return newHead;
}
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; }
}
}