这道题挺经典的,考察了链表的指针灵活运用。
#include<iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
ListNode *p,*L,*tmp,*q;
int length,i;
length=0;
p=head;
while(p)
{
length++;
p=p->next;
}
L=(ListNode*)malloc(sizeof(struct ListNode));
L->next=NULL;//L是逆转链表
tmp=L;//tmp是临时链表用来存放逆转的k个元素
while(length-k>=0)//head剩余长度大于k时继续循环
{
for(i=0;i<k;i++)
{
q=head;
head=head->next;
q->next=tmp->next;
tmp->next=q; //采用头插法逆转元素
}
while(tmp->next)//将tmp清空到最后一个节点好连接下面的k个元素
tmp=tmp->next;
length=length-k;
}
if(head)//原来的链表还有元素时直接接在链表尾部
tmp->next=head;
return L->next;
}
};
int main()
{
ListNode* L,*result,*p,*q;
int N,i,temp,k;
Solution solve;
cin>>N;
cin>>k;
L=(ListNode*)malloc(sizeof(struct ListNode));
L->next=NULL;
p=L;
for(i=0;i<N;i++)
{
cin>>temp;
q=(ListNode*)malloc(sizeof(struct ListNode));
q->val=temp;
q->next=NULL;
p->next=q;
p=q;
}
result=solve.reverseKGroup(L->next,k);
while(result)
{
cout<<result->val<<' ';
result=result->next;
}
return 0;
}
第二种方法是用栈的方法模拟,先进后出符合倒序,然后插入新的链表
#include<iostream>
#include<stack>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
stack<ListNode*> s;
ListNode *L,*start,*end,*q,*tmp;
int count;
L=(ListNode*)malloc(sizeof(ListNode));
L->next=NULL;
tmp=L;
start=head;
end=start;
while(1)
{
count=k;
while(count&&end)//start和end之间隔了k个元素
{
count--;
s.push(end);
end=end->next;
}
if(!count)
{
while(!s.empty())//采用尾插法插入
{
q=s.top();
s.pop();
tmp->next=q;
tmp=q;
}
start=end;
end=start;
}
else
break;
}
tmp->next=start;
return L->next;
}
};
int main()
{
ListNode* L,*result,*p,*q;
int N,i,temp,k;
Solution solve;
cin>>N;
cin>>k;
L=(ListNode*)malloc(sizeof(struct ListNode));
L->next=NULL;
p=L;
for(i=0;i<N;i++)
{
cin>>temp;
q=(ListNode*)malloc(sizeof(struct ListNode));
q->val=temp;
q->next=NULL;
p->next=q;
p=q;
}
result=solve.reverseKGroup(L->next,k);
while(result)
{
cout<<result->val<<' ';
result=result->next;
}
return 0;
}