061 - Rotate List
2015-12-30 16:33
190 查看
Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given
return
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* rotateRight(struct ListNode* head, int k)
{
struct ListNode *first, *second, *newhead;
int i;
if (!head) return head;
first = second = head;
int total = 0;
while (first) {
first = first->next;
total++;
}
k %= total;
i = k;
first = head;
while (second && i--) second = second->next;
if (!k || !second) return head;
while (second->next) {
first = first->next;
second = second->next;
}
newhead = first->next;
first->next = NULL;
second->next = head;
head = newhead;
return newhead;
}
For example:
Given
1->2->3->4->5->NULLand k =
2,
return
4->5->1->2->3->NULL.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* rotateRight(struct ListNode* head, int k)
{
struct ListNode *first, *second, *newhead;
int i;
if (!head) return head;
first = second = head;
int total = 0;
while (first) {
first = first->next;
total++;
}
k %= total;
i = k;
first = head;
while (second && i--) second = second->next;
if (!k || !second) return head;
while (second->next) {
first = first->next;
second = second->next;
}
newhead = first->next;
first->next = NULL;
second->next = head;
head = newhead;
return newhead;
}
相关文章推荐
- Style Scope Agile Edition―免费版商业智能产品
- postgresql学习line
- 解决android sdk无法访问Google的问题
- eclipse重新设置workspace路径
- JavaScriptCore在实际项目中的使用的坑
- AOP(2)
- iOS9 搜索API
- how to write one native program based on android source build system
- KVC设置unfinderKey和与系统关键字相同key的解决
- Linux下安装Tomcat7
- iOS通过dSYM文件分析crash
- cocostudio1.6UI编辑器中动画使用 cocos2dx3.3 播放问题记录
- 禁用其他应用程序, 代码块
- 转载For语句讲解
- 哈尔小波变换的原理及其实现(Haar)
- shader学习笔记二
- shareSDK
- Start your own JavaScript library using webpack and ES6
- 文法 分析 2
- 11 11 评价