Reverse Nodes in k-Group
2015-07-14 22:29
489 查看
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
If the number of nodes is not a multiple of k then left-out nodes in the end should remain asit is.
You may not alter the values in the nodes, onlynodes itself may be changed.
Only constant memory is allowed.
For example,
Given this linked list: 1->2->3->4->5
For k = 2, you should return: 2->1->4->3->5
For k = 3, you should return: 3->2->1->4->5
思路:本题要求空间复杂度为O(1),因此不能用栈来翻转k个元素。所以,本题真正的难点在于,如何用有限的指针,实现链表中k个元素的翻转。代码如下:
If the number of nodes is not a multiple of k then left-out nodes in the end should remain asit is.
You may not alter the values in the nodes, onlynodes itself may be changed.
Only constant memory is allowed.
For example,
Given this linked list: 1->2->3->4->5
For k = 2, you should return: 2->1->4->3->5
For k = 3, you should return: 3->2->1->4->5
思路:本题要求空间复杂度为O(1),因此不能用栈来翻转k个元素。所以,本题真正的难点在于,如何用有限的指针,实现链表中k个元素的翻转。代码如下:
struct ListNode *reverseknode(struct ListNode *begin, int k) { struct ListNode *endnext = begin; while(k && endnext) { k--; endnext = endnext->next; } if(k > 0) return begin; struct ListNode *reshead = endnext; struct ListNode *p, *q; p = begin; while(p != endnext) { q = p->next; p->next = reshead; reshead = p; p = q; } return reshead; } struct ListNode* reverseKGroup(struct ListNode* head, int k) { struct ListNode *reshead, *p, *q, *r; reshead = NULL; p = head; while(p != NULL) { q = reverseknode(p, k); if(reshead == NULL) reshead = q; else r->next = q; if(p == q) break; r = q; while(r != p) { r = r->next; } p = p->next; } return reshead; }
相关文章推荐
- Reverse Nodes in k-Group
- LeetCode题解——Remove Nth Node From End of List
- 3.osg中的CallBack回调、NodeVisitor与鼠标键盘的交互
- 美团酒店Node全栈开发实践
- NodeJs--Express新建项目
- Node:线段树的单点更新
- 【Count Complete Tree Nodes】cpp
- LintCode Insert a Node in a Binary Search Tree 在二叉查找树中插入节点
- WebSockets in Node.js for Windows 7
- ROS学习笔记10 - 编写编译和检验Service Node
- node.js不得不说的12点内容
- Node:RMQ问题之ST算法
- nodeJS代码实现计算交社保是否合适
- 使用forever管理nodejs应用
- 聊聊Node.js 独立日漏洞
- node.js开发中使用Node Supervisor实现监测文件修改并自动重启应用提高nodejs调试效率
- Node.js ORM框架:ORM2
- 【leetcode】Populating Next Right Pointers in Each Node II
- PM2 nodejs 学习(一)
- node 异步回调解决方法之yield