61. Rotate List
来源:互联网 发布:知乎怎么匿名 编辑:程序博客网 时间:2024/06/13 23:12
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有可能大于n。然后就是用快慢指针。
/** * 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 || head->next == NULL || k == 0) return head; int length = 0; ListNode* tmp = head; while(tmp != NULL) { tmp = tmp->next; length++; } int n = k%length; //k有可能大于n if(n == 0) return head; ListNode* fast = head; for(int i = 0; i < n; i++) { fast = fast->next; } ListNode* slow = head; while(fast->next !=NULL) { fast = fast->next; slow = slow->next; } fast->next = head; head = slow->next; slow->next = NULL; return head; }};
0 0
- [LeetCode]61.Rotate List
- 61. Rotate List
- LeetCode --- 61. Rotate List
- [Leetcode] 61. Rotate List
- 61. Rotate List
- [leetcode] 61.Rotate List
- [leetcode] 61. Rotate List
- 61. Rotate List
- leetcode 61. Rotate List
- LeetCode 61. Rotate List
- [leetcode] 61. Rotate List
- 61. Rotate List
- 61. Rotate List
- 61. Rotate List LeetCode
- leetcode 61. Rotate List
- 61. Rotate List
- 61. Rotate List
- 61. Rotate List
- Linux安装speedtest-cli测试网速
- Java实习面试的那些事(四)
- 核心动画 -- CAAnimationGroup简介
- 改进版臭事百科爬虫
- 漫谈数据库索引
- 61. Rotate List
- HTML笔记
- a标签href跳转---传值---禁止单引号
- java 中IO 流的知识
- 如何在 Kaggle 首战中进入前 10%
- CI3.0笔记
- iOS 数组遍历查询的几个方法
- windows api实现目录或文件读取
- Swift中随机数的使用,对不同类型随机数进行封装调用