leetcode - Rotate List
2016-04-15 17:07
204 查看
Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given
return
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; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: ListNode *rotateRight(ListNode *head, int k) { if(head == NULL || head->next == NULL || k == 0) return head; ListNode *p = head,*q = NULL; int ListNodeLength = 0; while(p != NULL) { ListNodeLength++; q = p; p = p->next; } k %= ListNodeLength; p = head; for(int i = 0; i < ListNodeLength - k - 1; i++) { p = p->next; } q->next = head; head = p->next; p->next = NULL; return head; } };
相关文章推荐
- 返回一个一维整数数组中最大子数组的和2
- 安装64位mysql5.626
- 被劫持的浏览器首页
- 4456: [Zjoi2016]旅行者 分治+最短路
- 在UWP中使用RichEditBox只读时图片显示问题(最后有关于RichEditBox颜色问题的解决方案)
- java学习总结(3)
- 237.LeetCode Delete Node in a Linked List(easy)[单链表 删除节点]
- byte、二进制、十进制数值之间的转换
- 方法:Mac终端控制文件显隐性
- Spring事务配置的五种方式
- 用代码创建一个空的工程
- 消息队列系列(二):.Rabbitmq的使用及Web监控工具使用
- smokeping对网络进行监控
- 【QT】:QT实现关联和解决关联
- centOS安装与配置minicom(串口转USB)
- Linux上安装nodejs
- Employment Planning DP
- Maven提高篇系列之一——多模块 vs 继承
- cvThreshold函数使用与注意事项
- 第四章: 数组