61.旋转链表 C++实现LeetCode
C++实现LeetCode(61.旋转链表),博智网带你了解详细信息 。
[LeetCode] 61. Rotate List 旋转链表Given the head of a linked list, rotate the list to the right by k places.
Example 1:

文章插图

文章插图

文章插图
Input: head = [0,1,2], k = 4Constraints:
Output: [2,0,1]
- The number of nodes in the list is in the range [0, 500].
- -100 <= Node.val <= 100
- 0 <= k <= 2 * 109
解法一:
class Solution {public:ListNode *rotateRight(ListNode *head, int k) {if (!head) return NULL;int n = 0;ListNode *cur = head;while (cur) {++n;cur = cur->next;}k %= n;ListNode *fast = head, *slow = head;for (int i = 0; i < k; ++i) {if (fast) fast = fast->next;}if (!fast) return head;while (fast->next) {fast = fast->next;slow = slow->next;}fast->next = head;fast = slow->next;slow->next = NULL;return fast;}};
【61.旋转链表 C++实现LeetCode】这道题还有一种解法,跟上面的方法类似,但是不用快慢指针,一个指针就够了,原理是先遍历整个链表获得链表长度n,然后此时把链表头和尾链接起来,在往后走 n - k%n 个节点就到达新链表的头结点前一个点,这时断开链表即可,代码如下:
class Solution {public:ListNode *rotateRight(ListNode *head, int k) {if (!head) return NULL;int n = 1;ListNode *cur = head;while (cur->next) {++n;cur = cur->next;}cur->next = head;int m = n - k % n;for (int i = 0; i < m; ++i) {cur = cur->next;}ListNode *newhead = cur->next;cur->next = NULL;return newhead;}};
到此这篇关于C++实现LeetCode(61.旋转链表)的文章就介绍到这了,更多相关C++实现旋转链表内容请搜索趣讯吧以前的文章或继续浏览下面的相关文章希望大家以后多多支持趣讯吧!
- cdr文件该咋旋转
- cdr文件怎么旋转复制
- cdr该咋地才可以旋转复制
- cdr该怎么旋转
- cdr该咋地才可以旋转
- cdr该咋旋转复制
- cdr文件该怎么旋转
- cdr文件复制该怎么样旋转
- 旋转的反义词是什么
- 华为手机怎么设置自动旋转
