61-Rotate list
来源:互联网 发布:什么盒子能接猫的网络2 编辑:程序博客网 时间:2024/06/05 15:07
难度:medium
类别:linked list
1.题目描述
Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.
2.算法分析
(1)处理链表为空以及链表只有一个节点的情况
(2)k的值可能超过count,所以k %= count
(3)处理断开处前一个节点的next
(4)让最后一个节点的next指向head
3.代码实现
#include <iostream>using namespace std;struct ListNode { int val; ListNode *next; ListNode(int x) :val(x), next(NULL) {}};ListNode* rotateRight(ListNode* head, int k) { if (head == NULL || head->next == NULL) return head; int count = 0; // count list length ListNode* temp = head; while (temp != NULL) { count++; temp = temp->next; } // k may > count; k = k % count; if (k == 0) return head; int num = 1; temp = head; // 断开处的next处理 while (num != count - k) { num++; temp = temp->next; } ListNode* begin = temp->next; ListNode* result = begin; temp->next = NULL; while (begin->next != NULL) { begin = begin->next; } // 尾部节点的next设置为head begin->next = head; return result;}void printList(ListNode* head) { while (head != NULL) { cout << head->val << " "; head = head->next; } cout << endl;}int main() { int n, num, k; cin >> n >> k; ListNode* head = NULL; ListNode* temp = NULL; for (int i = 0; i < n; ++i) { cin >> num; if (i == 0) { head = new ListNode(num); temp = head; } else { head->next = new ListNode(num); head = head->next; } } printList(temp); temp = rotateRight(temp, k); printList(temp); system("pause"); return 0;}
阅读全文
0 0
- LeetCode 61: Rotate List
- [Leecode 61] Rotate List
- [leetcode 61] Rotate List
- [leetcode #61]Rotate List
- 61Rotate List
- leetcode || 61、Rotate List
- LeeCode 61 Rotate List
- 61 Rotate List
- leetcode[61]:Rotate List
- LeetCode 61: Rotate List
- LeetCode(61) Rotate List
- LeetCode 61 Rotate List
- leetcode 61: Rotate List
- Leetcode#61||Rotate List
- [Leetcode]#61 Rotate List
- 61Rotate List
- leetcode 61:Rotate List
- 【leetcode】【61】Rotate List
- 第九周项目1
- 53.Oracle杂记——Oracle常用动态视图v$tempstat
- js实现手机横竖屏事件
- 54.Oracle杂记——Oracle常用动态视图v$tempfile
- 设计模式之命令模式
- 61-Rotate list
- 新领域的一个小白
- 函数/代码安全、malloc的低层实现
- 使用整形和浮点型
- 文章标题
- 55.Oracle杂记——Oracle常用动态视图v$PGA_TARGET_ADVICE
- 56.Oracle杂记——Oracle常用动态视图v$db_cache_advice
- 图像数据集的扩展
- Android图片加载神器之Fresco,基于各种使用场景的讲解