赞
踩
思路
(1)缩小k
(2)找到新头结点和新头结点的上一个节点
(3)旋转操作
实现
class Solution { // 长度为5时: // + 移动0次、5次、10次是一样的效果 // + 移动1次、6次、11次是一样的效果 // + ... // + 移动4次,9次,...是一样的效果 int getLength(ListNode* head){ if(head == nullptr){ return 0; } return 1 + getLength(head->next); } struct Info{ ListNode *newHead; ListNode *preNode; Info(ListNode *preNode, ListNode *newHead) : preNode(preNode), newHead(newHead){ } }; // 1, 2, 3, 4, 5 --> 当k = 0时,走5步,得到newHead = null // 5, 1, 2, 3, 4 --> 当k = 1时,走4步,得到newHead = 5 // 4, 5, 1, 2, 3 --> 当k = 2时,走3步,得到newHead = 4 Info *moveKStep(ListNode* prev, ListNode* curr, int k){ if(k == 0){ return new Info(prev, curr); } return moveKStep(curr, curr->next, k - 1); } ListNode *moveTail(ListNode* curr){ if(curr->next == nullptr){ return curr; } return moveTail(curr->next); } public: ListNode* rotateRight(ListNode* head, int k) { if(head == nullptr || k == 0){ return head; } ListNode *curr = nullptr, *oldHead = head, *newTail = nullptr; int len = getLength(curr = head); k = k % len; Info *info = moveKStep(nullptr, curr = head, len - k); if(info->newHead == nullptr){ return head; } info->preNode->next= nullptr; // [1, 2, 3, 4] newTail = moveTail(curr = info->newHead); // [5] newTail->next = oldHead; return info->newHead; } };
实现二
class Solution { public: ListNode* rotateRight(ListNode* head, int k) { if(head == nullptr || k == 0){ return head; } int n = 0; ListNode *curr = head; while (curr){ ++n; curr = curr->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 = nullptr; return fast; } };
思路:
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 = nullptr; return newHead; } };
题目 | 思路 |
---|---|
leetcode:61. 旋转链表 Rotate List | 先遍历整个链表获得链表长度n,然后把链表头部和尾部连接起来,在往后走n - k % n个节点就到达新链表的头结点的前一个节点,这时断开链表即可 |
leetcode:189. 旋转数组 | 多次反转:先反转全部,然后反转前k个,最后反转剩余的;下标连环怼;使用临时数组 |
leetcode:151. 给定字符串, 反转字符串中的单词(需要去除多余空格) | 源字符串为:"the sky is blue ";移除多余空格:“the sky is blue”;字符串反转:“eulb si yks eht”;单词反转:“blue is sky the” |
leetcode:186. 给定char数组,翻转字符串里的单词 II | 先把每个单词翻转一遍,再把整个字符串翻转一遍,或者也可以调换个顺序,先翻转整个字符串,再翻转每个单词 |
leetcode:557. 给定字符串, 反转字符串中的单词 III | |
leetcode:328. 奇偶链表 Odd Even Linked List | |
leetcode:725. 分隔链表 Split Linked List in Parts |
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。