Reverse Nodes in k-Group
2015-07-11 20:30
555 查看
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
ListNode* p=head;
int len=0;
if(head==NULL||head->next==NULL) return head;
while(p)
{
len++;
p=p->next;
}
int m=1,n=k;
while(n<=len)
{
head=reverseBetween(head,m,n);
m=m+k;
n=n+k;
}
return head;
}
ListNode* reverseList(ListNode* head) {
if(head==NULL) return head;
if(head->next==NULL) {return head;}
ListNode* p=head;
ListNode* p1;
ListNode* p2;
p1=p->next;
p2=p->next->next;
p->next=NULL;
while(p2)
{
p1->next=p;
p=p1;
p1=p2;
p2=p2->next;
}
p1->next=p;
return p1;
}
ListNode* reverseBetween(ListNode* head, int m, int n) {
int count=1;
ListNode* p=head,*pre,*plast,*head1,*head2;
if(head==NULL||head->next==NULL) return head;
// ListNode* pre;
while(count<m-1)
{
p=p->next;
count++;
}
pre=p;
head1=p->next;
if(m==1)
head1=head;
while(count<n)
{
p=p->next;
count++;
}
plast=p->next;
p->next=NULL;
head2=reverseList(head1);
if(m==1&&n!=1){ head1->next=plast;return head2;}
else{
pre->next=head2;
head1->next=plast;}
return head;
}
};
public:
ListNode* reverseKGroup(ListNode* head, int k) {
ListNode* p=head;
int len=0;
if(head==NULL||head->next==NULL) return head;
while(p)
{
len++;
p=p->next;
}
int m=1,n=k;
while(n<=len)
{
head=reverseBetween(head,m,n);
m=m+k;
n=n+k;
}
return head;
}
ListNode* reverseList(ListNode* head) {
if(head==NULL) return head;
if(head->next==NULL) {return head;}
ListNode* p=head;
ListNode* p1;
ListNode* p2;
p1=p->next;
p2=p->next->next;
p->next=NULL;
while(p2)
{
p1->next=p;
p=p1;
p1=p2;
p2=p2->next;
}
p1->next=p;
return p1;
}
ListNode* reverseBetween(ListNode* head, int m, int n) {
int count=1;
ListNode* p=head,*pre,*plast,*head1,*head2;
if(head==NULL||head->next==NULL) return head;
// ListNode* pre;
while(count<m-1)
{
p=p->next;
count++;
}
pre=p;
head1=p->next;
if(m==1)
head1=head;
while(count<n)
{
p=p->next;
count++;
}
plast=p->next;
p->next=NULL;
head2=reverseList(head1);
if(m==1&&n!=1){ head1->next=plast;return head2;}
else{
pre->next=head2;
head1->next=plast;}
return head;
}
};
相关文章推荐
- nodejs - 升级
- [LeetCode] Populating Next Right Pointers in Each Node II
- Node.js 之基于文件的模块系统
- [LeetCode] Populating Next Right Pointers in Each Node
- node在Fedora 22系统下开发环境搭建
- Count Complete Tree Nodes
- 记 Ubuntu14.04 Monodevelop 安装的两个问题
- [LeetCode][Java] Reverse Nodes in k-Group
- Node.js执行存储过程
- node.js的npm安装
- 在nodeschool学习git
- 一次使用NodeJS实现网页爬虫记
- Nodejs中when库的实例介绍
- 查看CPU处于哪个node
- nodejs【伪】入门教程
- LeetCode Count Complete Tree Nodes
- ubuntu nodejs + express4.x 安装 测试
- 通过官方网站的资料学习node
- Leetcode#24 Swap Nodes in Pairs
- Webpack 性能优化 (一)(使用别名做重定向)