LeetCode 61. Rotate List
来源:互联网 发布:免费刷q币软件 编辑:程序博客网 时间:2024/05/19 18:47
61. Rotate List
一、问题描述
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
.
三、解题思路
这道题的意思是:把后面的k个数字移动到前面去。如果k比链表的长度要大,就需要取模运算。(吃了没文化的亏╮(╯▽╰)╭)
Tow Pointers有人用fast slow指针来找末尾的那个位置,我还不知道怎么找。。
- 算法思路:遍历一遍链表,计算出链表的长度并把tail->next = head 形成一个循环链表。然后再从头开始往后遍历链表,走 length - k % length步,就找到新的链表尾部了,把链表断开就行了。想清楚了题目的意思其实并不难。
/** * 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 == NULL)return head; ListNode* tail = head, *nTail = head; int length = 1; while(tail->next){ tail=tail->next; length++; } tail->next = head; int steps = length - k % length; while (--steps){ nTail = nTail->next; } head = nTail->next; nTail->next = NULL; return head; }};
阅读全文
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
- 配置torch、nccl环境遇到的问题
- python3.6+pyqt5 IDE: Pycahrm+Qtdesign 快速开发GUI程序学习资源
- 大型JavaScript应用程序架构模式
- Java成员变量、局部变量、静态变量、成员方法、全局方法等概念的区别
- dwr3.0推送框架的入门搭建及解答(最新)
- LeetCode 61. Rotate List
- epoll LT/ET 深入剖析
- 获取.properties 配置中的属性名
- css笔记
- 这可能是最好的RxJava 2.x 入门教程(二)
- android 调试常用命令
- android 添加帐户具体步骤
- fastjson反序列化ZonedDateTime格式的时间
- Maven 参考知识