本文已收录到:LeetCode刷题 专题
- 42. 接雨水 (Trapping Rain Water)
- [LeetCode] 2. 两数相加 2. Add Two Numbers
- [LeetCode] 19. 删除链表的倒数第N个节点 19. Remove Nth Node From End of List
- [LeetCode] 21. 合并两个有序链表(Merge Two Sorted Lists)
- [LeetCode] 24. 两两交换链表中的节点(Swap Nodes in Pairs)
- [LeetCode] 61. 旋转链表(Rotate List)
- [LeetCode] 82. 删除排序链表中的重复元素 II(Remove Duplicates from Sorted List II)
- [LeetCode] 83. 删除排序链表中的重复元素(Remove Duplicates from Sorted List)
- [LeetCode] 86. 分隔链表(Partition List)
- [LeetCode] 206. 反转链表(Reverse Linked List)
- [LeetCode] 92. 反转链表 II(Reverse Linked List II)
- [LeetCode] 147. 对链表进行插入排序(Insertion Sort List)
- [LeetCode] 203. 移除链表元素(Remove Linked List Elements)
- [LeetCode] 160. 相交链表(Intersection of Two Linked Lists)
- [LeetCode] 237. 删除链表中的节点 (Delete Node in a Linked List)
- [LeetCode] 328. 奇偶链表 (Odd Even Linked List)
- [LeetCode] 876. 链表的中间结点 (Middle of the Linked List)
- [LeetCode] 1290. 二进制链表转整数 (Convert Binary Number in a Linked List to Integer)
- [LeetCode] 141. 环形链表 (Linked List Cycle)
- [LeetCode] 142. 环形链表 II (Linked List Cycle II)
- [LeetCode] 283. 移动零 (Move Zeroes)
- [LeetCode] 496. 下一个更大元素 I (Next Greater Element I)
- [LeetCode] 503. 下一个更大元素 II (Next Greater Element II)
- [LeetCode] 456. 132模式 (132 Pattern)
- [LeetCode] 20. 有效的括号 (Valid Parentheses)
- [LeetCode] 94. 二叉树的中序遍历 (Binary Tree Inorder Traversal)
- [LeetCode] 144. 二叉树的前序遍历 (Binary Tree Preorder Traversal)
- [LeetCode] 145. 二叉树的后序遍历 (Binary Tree Postorder Traversal)
[title]题目[/title]
给定一个链表,旋转链表,将链表每个节点向右移动 k 个位置,其中 k 是非负数。
示例 1:
输入: 1->2->3->4->5->NULL, k = 2
输出: 4->5->1->2->3->NULL
解释:
向右旋转 1 步: 5->1->2->3->4->NULL
向右旋转 2 步: 4->5->1->2->3->NULL
示例 2:
输入: 0->1->2->NULL, k = 4
输出: 2->0->1->NULL
解释:
向右旋转 1 步: 2->0->1->NULL
向右旋转 2 步: 1->2->0->NULL
向右旋转 3 步: 0->1->2->NULL
向右旋转 4 步: 2->0->1->NULL
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/rotate-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
[title]视频讲解[/title]
[bilibili cid=”” page=”1″]752530187[/bilibili]
[title]代码[/title]
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* rotateRight(ListNode* head, int k) { if (head == nullptr) { return head; } ListNode* fast = head; ListNode* slow = head; //求链表长度 int n = 1; ListNode* len = head; while (len->next != nullptr) { n++; len = len->next; } k = k % n; if (k == 0) { return head; } for (int i = 0; i < k; i++) { fast = fast->next; } while (fast->next != nullptr) { fast = fast->next; slow = slow->next; } ListNode* newHead = slow->next; slow->next = nullptr; fast->next = head; return newHead; } };