「LeetCode」61. 旋转链表
2023-09-27 14:27:52 时间
- 旋转链表
给你一个链表的头节点 head ,旋转链表,将链表每个节点向右移动 k 个位置。
示例 1:
输入:head = [1,2,3,4,5], k = 2
输出:[4,5,1,2,3]
示例 2:
输入:head = [0,1,2], k = 4
输出:[2,0,1]
题解:
/**
* 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 (head == null || head.next == null)return head;
int len =1;
ListNode oldTail = head;
while (oldTail.next!=null) {
oldTail = oldTail.next;
len++;
}
oldTail.next = head;
ListNode newTail = head;
for(int i =0; i < len - k% len -1; i++){
newTail = newTail.next;
}
ListNode newHead = newTail.next;
newTail.next =null;
return newHead;
}
}
详尽解析版:
class Solution {
public ListNode rotateRight(ListNode head, int k) {
// 1. 特判
if(k == 0 || head == null || head.next == null){
return head;
}
// 2. 计算出原链表的长度为n
int n = 1;
ListNode iter = head;
while(iter.next != null){
iter = iter.next;
n++; // 此时n记录的是链表的末尾节点
}
// 3. 找到移动k位后新链表的最后一个节点
int add = n - k % n; // add 记录的是新链表的最后一个节点
if(add == n){ // 如果k 刚好为n的整数倍数,新链表将于原链表相同
return head; // 直接返回原链表即可
}
// 4. 处理逻辑
iter.next = head; // 将当前链表闭合为环
while(add-- > 0){ // 将iter指向新链表的最后一个节点位置
iter = iter.next;
}
ListNode ret = iter.next; // 此时 ret为移动k位后新链表的头
iter.next = null; // 将环断开
return ret; // 返回新链表
}
}
相关文章
- LeetCode每日一练 —— 链表中倒数第 k 个结点
- 【LeetCode】环形链表 II [M](链表)
- 【LeetCode】接雨水 II [H](堆)
- 【LeetCode】交错字符串 [M](动态规划)
- 【LeetCode】合并K个升序链表(使用优先级队列实现)
- LeetCode 21. 合并两个有序链表 题解 C++
- leetCode 61.Rotate List (旋转链表) 解题思路和方法
- (LeetCode)两个链表的第一个公共节点
- LeetCode_双指针_中等_24.两两交换链表中的节点
- LeetCode_优先级队列_中等_373.查找和最小的 K 对数字
- LeetCode_数据结构设计_中等_341. 扁平化嵌套列表迭代器
- LeetCode_排序_中等_179.最大数
- LeetCode刷题(16)【简单】移除链表元素&&回文链表&&删除链表中的结点
- LeetCode·每日一题·1796.字符串中第二大的数字·模拟
- 「LeetCode」24. 两两交换链表中的节点
- 「LeetCode」92. 反转链表 II
- 「LeetCode」206. 反转链表
- [LeetCode] 86. Partition List 划分链表
- [LeetCode] 61. Rotate List 旋转链表
- [LeetCode] 650. 2 Keys Keyboard 两键的键盘
- [LeetCode] 387. First Unique Character in a String 字符串的第一个唯一字符
- [LeetCode] 340. Longest Substring with At Most K Distinct Characters 最多有K个不同字符的最长子串
- [LeetCode] 206. Reverse Linked List 反向链表
- [LeetCode] 454. 4Sum II 四数之和II
- leetcode 141 环形链表
- leetcode 92 翻转链表II
- leetcode 509 斐波那契数
- leetcode 134 加油站
- leetcode 77组合