61-Rotate List
来源:互联网 发布:李乐的霍去病 知乎 编辑:程序博客网 时间:2024/06/07 00:38
题目
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.
分析
方法的思路是遍历一遍找到尾结点,并记录链表长度,然后连接成一个环,再遍历一遍找到第n-k个结点,并把链表从中间断开。
实现
class Solution {public: ListNode* rotateRight(ListNode* head, int k) { if (head == NULL || head->next == NULL || k == 0) return head; int len = 1; ListNode *tail = head; while (tail->next) { tail = tail->next; len++; } tail->next = head; k = k%len; for (int i = 0; i < len - k; i++) tail = tail->next; head = tail->next; tail->next = NULL; return head; }};
阅读全文
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
- MyBatis常用对象SqlSessionFactory和SqlSession介绍和运用
- mysql数据库优化--(3)设计 范式 Normal Format, 规范的格式
- 56-Merge Intervals && 57-Insert Interval
- 写给非专业人士看的 Shadowsocks 简介
- PAT练习-程序运行时间
- 61-Rotate List
- 20170623
- 三元式,四元式,逆波兰表达式
- 62-Unique Paths
- CDN 是个啥
- 关于PCA算法学习心得
- 在windows电脑上配置自动打包
- 如何下载百度地图中的矢量POI兴趣点
- JQuery2------6.22