[LeetCode] Rotate List
来源:互联网 发布:电脑电视台直播软件 编辑:程序博客网 时间:2024/06/07 19:21
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是非负数。
看上面的例子,如果能够找到倒数第k + 1个节点和最后一个节点就可以了,假设p指向该节点,q指向尾节点,那么进行如下操作即可将链表旋转。
q->next = head;head = p->next;p->next = NULL;那么问题就变成了如何找到倒数第k + 1个节点和最后一个节点呢?从后面开始计数,可以使用栈来进行辅助计数。
首先将所有节点指针都入栈,入栈完毕之后,栈顶元素就是尾节点的指针,然后依次出栈,出k + 1次,最后一次出栈得到的节点就是倒数第k + 1个节点。
class Solution {public: ListNode *rotateRight(ListNode *head, int k) { stack<ListNode *> sta; ListNode *pnode = head, *rear = NULL; int len = 0; if(head == NULL || k == 0) return head; while(pnode) { sta.push(pnode); pnode = pnode->next; ++len; } k %= len; ++k; if(!sta.empty()) rear = sta.top(); while(k--) { pnode = sta.top(); sta.pop(); } rear->next = head; head = pnode->next; pnode->next = NULL; return head; }};
0 0
- [leetcode][list] Rotate List
- LeetCode: Rotate List
- LeetCode Rotate List
- LeetCode : Rotate List
- [Leetcode] Rotate List
- [LeetCode] Rotate List
- [leetcode] Rotate List
- leetcode 70: Rotate List
- [Leetcode] Rotate List
- 【leetcode】Rotate List
- [LeetCode]Rotate List
- [leetcode]Rotate List
- LeetCode-Rotate List
- [leetcode] Rotate List
- LeetCode - Rotate List
- LeetCode:Rotate List
- LeetCode 61: Rotate List
- leetcode之Rotate List
- 机器指令 汇编 优化 编译概念的理解!
- HTTP Header('Content-Type:application/xxx')
- <a href="#">禁止跳到页面顶端的解决办法
- 收房程序
- 保持长宽比 对背景图像进行修改android:scaleType="fitXY"
- [LeetCode] Rotate List
- gflags使用
- Android的一些设备信息
- 鼠标悬停在小图上,自动出现大图的代码
- Jquery表单插件ajaxForm用法详解
- 部分保留".cn和.中国"域名开放注册
- 毛坯房收楼注意事项
- 软件设计通用原则整理
- 蜗牛—cocos2dx之2.2以上版本新建项目