Rotate List -- leetcode
来源:互联网 发布:美科网络 编辑:程序博客网 时间:2024/06/16 06:00
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
.
在leetcode上实际执行时间为16ms。
基本思路:
1. 统计链表长度 count
2.首尾相接,做成循环链表。
3.从头再移动到第 count - k 结点,在此断开。
/** * 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 || !head->next || !k) return head; int count = 1; ListNode *p = head; while (p->next) { ++count; p = p->next; } p->next = head; k = k % count; k = count - k; while (k--) p = p->next; head = p->next; p->next = 0; return head; }};
0 0
- [leetcode][list] Rotate List
- LeetCode: Rotate List
- LeetCode Rotate List
- LeetCode : Rotate List
- [Leetcode] Rotate List
- [LeetCode] Rotate List
- [leetcode] Rotate List
- leetcode 70: Rotate List
- [Leetcode] Rotate List
- 【leetcode】Rotate List
- [LeetCode]Rotate List
- [leetcode]Rotate List
- LeetCode-Rotate List
- [leetcode] Rotate List
- LeetCode - Rotate List
- LeetCode:Rotate List
- LeetCode 61: Rotate List
- leetcode之Rotate List
- Oracle EBS Form个性化调用自定义程序库入门
- 华为odex 合并jar失败
- STL库中简单的list类模板示例和一个小的延时程序
- 深入图解字符集与字符集编码(一)——charset vs encoding(出处:http://my.oschina.net/goldenshaw/blog/304493)
- 调用百度地图API进行地理编码和反地理编码(二)——批量处理
- Rotate List -- leetcode
- Druid数据库连接池使用
- 数据结构(三)-链队
- 移动设备和SharePoint 2013 - 第1部分:概述
- Perl脚本学习心得
- qemu运行xp虚拟机
- 二维数组的new 和 delete
- c 宏定义中的 do {} while(0) 的使用
- 对++运算符的思考