【Leetcode】之Reverse Nodes in k-Group
2015-11-18 10:28
911 查看
一.问题描述
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 as it is.
You may not alter the values in the nodes, only nodes 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
二.我的解题思路
链表的问题都很直观。对于这道题目,很自然的想到分治递归的办法。以k个节点为一个单位,进行reverse求解。测试通过的程序如下:/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* reverseKGroup(ListNode* head, int k) { ListNode* curr,* next,* tmp; ListNode* st,* end; int cnt=0; curr=head; if(curr==NULL) return NULL; while(curr!=NULL){ cnt++; if(cnt==k) break; curr=curr->next; } //judge if there exists k nodes if(cnt==k){ //if exists st=head;cnt=1;end=head; while(cnt<k){ next=end->next; tmp=next->next; next->next=st; end->next=tmp; st=next; cnt++; } if(end->next==NULL) return st; end->next=reverseKGroup(end->next,k); return st; } return head; } };
相关文章推荐
- node.js学习资料
- 安装HomeBrew+ node + express
- 认识DOM的三大节点:元素节点,文本节点,属性节点以及nodeName,nodeType,nodeValue的区别
- Node.js Web框架之Express
- hook_load = hook_node_load
- copyFromLocal异常DataNode启动不了
- LeetCode237:Delete Node in a Linked List
- 关于机房交换机故障导致HDFS NameNode挂掉的问题(续)
- Node.js加密算法
- dom4j获取某个已知节点的值+循环名字相同的节点
- 用nodejs搭建一个简单的服务监听程序
- node.js抓取并分析网页内容有无特殊内容的js文件
- nodeJs学习
- parentNode parentElement childNodes children
- [LintCode] Remove Nth Node From End of List
- Node v0.12.5 稳定版发布
- MEAN教程2-Nodejs安装
- node.js抓取并分析网页内容有无特殊内容的js文件
- [神器推荐]node-webkit:跨平台桌面web应用的神器,非常有用(转)
- 查看job的详细日志出错: Aggregation is not enabled. Try the nodemanager at d2.hadoop:42812