[LeetCode] Reverse Nodes in k-Group
2015-07-06 14:54
507 查看
Well, since the
For the example list
The code is as follows.
headpointer may also be modified, we create a
new_headthat points to it to facilitate the reverse process.
For the example list
1 -> 2 -> 3 -> 4 -> 5in the problem statement, it will become
0 -> 1 -> 2 -> 3 -> 4 -> 5(we init
new_head -> valto be
0). Then we set a pointer
preto
new_headand another
curto
head. Then we insert
cur -> nextafter
prefor
k - 1times if the current node
curhas at least
knodes after it (including itself). After reversing one
k-group, we update
preto be
curand
curto be
pre-> nextto reverse the next
k-group.
The code is as follows.
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
if (!hasKNodes(head, k)) return head;
ListNode* new_head = new ListNode(0);
new_head -> next = head;
ListNode* pre= new_head;
ListNode* cur = head;
while (hasKNodes(cur, k)) {
for (int i = 0; i < k - 1; i++) {
ListNode* temp = pre-> next;
pre-> next = cur -> next;
cur -> next = cur -> next -> next;
pre-> next -> next = temp;
}
pre= cur;
cur = pre-> next;
}
return new_head -> next;
}
private:
bool hasKNodes(ListNode* node, int k) {
int cnt = 0;
while (node) {
cnt++;
if (cnt >= k) return true;
node = node -> next;
}
return false;
}
};
相关文章推荐
- nodejs爬虫系统
- [LeetCode] Swap Nodes in Pairs
- Nodejs和npm学习
- leetcode Populating Next Right Pointers in Each Node 树 队列应用
- 使用DNode实现php和nodejs之间通信的简单实例
- 学习老外用webstorm开发nodejs的技巧--代码提示DefinitelyTyped
- iPhone手机上搭建nodejs服务器步骤方法
- 使用DNode实现php和nodejs之间通信的简单实例
- Hadoop Cluster启动后数据节点(Datanode)进程状态丢失
- Node Glob
- ROS学习手记 - 3 理解ROS中的基本概念_ROS_Nodes
- NodeJS优缺点及适用场景讨论
- sublime快捷方式和node.js
- Nodejs负载均衡:haproxy,slb以及node-slb - i5ting的个人空间 - 开源中国社区
- ovirt-node 之build分析
- LeetCode 之 Populating Next Right Pointers in Each Node I II — C++ 实现
- node.js在前端这个行业中所占的比例
- node C++扩展(2) 尝试翻译node官网文档
- node.js C++ 扩展
- 【leetcode】Populating Next Right Pointers in Each Node I&&II