【Leetcode】之Reverse Nodes in k-Group
来源:互联网 发布:芒果tv破解版mac 编辑:程序博客网 时间:2024/06/03 20:24
一.问题描述
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; }};
0 0
- LeetCode之Reverse Nodes in k-Group
- leetcode之Reverse Nodes in k-Group
- LeetCode之Reverse Nodes in k-Group
- 【Leetcode】之Reverse Nodes in k-Group
- leetcode之Reverse Nodes in k-Group
- leetcode之Partition List,Reverse Nodes in k-Group
- LeetCode 之 Reverse Nodes in k-Group — C 实现
- Leetcode之Reverse Nodes in k-Group (Hard)
- LeetCode第25题之Reverse Nodes in k-Group
- LeetCode进阶之路(Reverse Nodes in k-Group)
- LeetCode:Reverse Nodes in k-Group
- LeetCode: Reverse Nodes in k-Group
- LeetCode : Reverse Nodes in k-Group
- leetcode 42: Reverse Nodes in k-Group
- [Leetcode] reverse nodes in K-Group
- [LeetCode]Reverse Nodes in k-Group
- LeetCode-Reverse Nodes in k-Group
- LeetCode - Reverse Nodes in k-Group
- Eclipse上GIT插件EGIT使用手册
- 记Ubuntu 14.04 安装Myeclipse 2014+ 破解
- NSString和NSMutableString的使⽤ NSArray和NSMutableArray的初级使⽤
- android项目——透明圆角框的制作
- 使用DOS命令共享文件夹并设置共享权限
- 【Leetcode】之Reverse Nodes in k-Group
- x265 Documentation
- 用pycaffe绘制训练过程的loss和accuracy曲线
- SAX解析和生成XML文档
- 逻辑电路 - 或非门Nor Gate
- mac下快速锁屏技巧
- Android Studio 使用2-HelloWorld
- DB2错误代码大全
- vslam与SFM区别与联系 2010