61. Rotate List
来源:互联网 发布:更换软件图标 编辑:程序博客网 时间:2024/06/06 01:46
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是怎么定义的,后来看了别人的博客才知道,需要旋转的次数kk = k%len(list).因此得到以下自己编写的答案:
接下来就是两个指针之间相差K,是 求链表中倒数第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 == NULL|| head->next == NULL) return head; int sum = 0; ListNode* p = head; ListNode* p1 = head, *p2 = head; while(p){ ++sum; p = p->next; } p = head; int kk = k % sum; if(kk == 0) return head; else{ while(kk--) p2 = p2->next; while(p2->next != NULL){ p1 = p1->next; p2 = p2->next; } p2->next = head; head = p1->next; p1->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
- 剑指offer-面试题4.替换空格
- 关于vertical-align实现图片垂直居中
- BroadcastReciever广播接收者
- C++服务器(六):socket 异步模型与select 的实现
- Arrays类应用
- 61. Rotate List
- spring MVC报错 Expected MultipartHttpServletRequest: is a MultipartResolver configured?
- DCOS之Mesos-DNS介绍
- JavaScript之继承和prototype
- 剑指offer-面试题5.从尾到头打印链表
- bzoj 1715(spfa 判断负环)
- POJ2236Wireless Network(结构体,并查集)
- GDAL创建图像提示Driver xxx does not support XXX creation option的原因
- Java基础知识