Leetcode-61. Rotate List
来源:互联网 发布:mac抓取网页视频 编辑:程序博客网 时间:2024/06/05 03:19
解题思路:统计链表长度后,找到新链表首元素的位置。断开旧链表,链接新链表
class Solution {public: ListNode* rotateRight(ListNode* head, int k) { if(head==NULL) return head; ListNode *left = head,*right = head; int len = 1; while(right->next){ right = right->next; len++; } k = k%len; if(len==k) return head; for(int i=1;i<len-k;i++) left = left->next; if(right!=head){ right->next = head; head = left->next; left->next = NULL; } return head; }};
解题思路:之后看到别人提供的类似解题方法,更加的优化简洁。巧妙地利用了单来表的性质,将单链表首尾相连成环后找到新链表首元素的位置,切开链表环,返回新链表首元素地址。
class Solution {public: ListNode* rotateRight(ListNode* head, int k) { if(head==NULL) return head; ListNode *newh = head,*tail = head; int len = 1; while(tail->next){ tail = tail->next; len++; } k = k%len; if(len==k) return head; tail->next = head; for(int i=0;i<len-k;i++) tail = tail->next; newh = tail->next; tail->next = NULL; return newh; }};
0 0
- [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
- [leetcode] 61. Rotate List
- 61. Rotate List LeetCode
- 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
- [Leetcode]61. Rotate List
- LeetCode - 61. Rotate List
- D - Rectangles
- 联机Unity Profile性能调试技巧
- Apache Kafka笔记(一):基础架构
- javascript 笔记
- 构建基于 JPA 的 Hibernate 环境
- Leetcode-61. Rotate List
- selenium-java-Firefox 特殊异常:界面找不到元素
- 【通信框架】Google的开源通信框架protobuf概述
- [Codeforces734E]Anton and Tree 树的直径
- 《白说》---- 读书笔记
- spring中bean的生命周期详解
- vim各种命令
- Unity如何区分安卓、苹果设备是手机与平板?
- JAVA SE IO个人小结