[LeetCode]Rotate List
2015-10-27 23:33
477 查看
题目描述:(链接)
Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given
return
解题思路:
注意k会大于链表长度: k % length.
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->NULLand k =
2,
return
4->5->1->2->3->NULL.
解题思路:
注意k会大于链表长度: k % length.
/** * 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 || k == 0) return head; int length = 1; ListNode *cur = head; for (; cur->next != nullptr ; cur = cur->next) { ++length; } k = length - k % length; cur->next = head; for (int i =0; i < k; i++) { cur = cur->next; } head = cur->next; cur->next = nullptr; return head; } };
相关文章推荐
- Window 消息大全
- 互联网架构师必备技能(使用markdown编写)
- Objective-C 的Runtime的学习
- Android最小屏幕适配
- 论浪漫与现实
- cocos2dx3.3视频播放的实现VideoPlayer的使用
- Android 亲身经历面试题总结(第二回合)
- Java记录 -46- ArrayList源码剖析
- [线段树点修改]动态最大连续和(Ray,Pass me the Dishes, LA 3938)
- fs4412开发板学习笔记(五)
- Playing audio from Node.js using Edge.js
- 小记天池大赛
- Github使用教程
- 文本相似性问题个人见解
- HDU3953(找规律,坑~)
- Xcode The identity used to sign the executable is no longer valid. 错误解决
- HDU 4771 (DFS+BFS)
- GET请求和POST请求剖析
- 全局函数的Result一定要每次都初始化,否则上次的结果会被保持到下一次继续使用
- GitHub