经典dummyhead题目
每隔n个节点建立一个dummyhead,使用头插法进行连接以倒置顺序,后连接在前段的后面
#include<iostream>
#include<vector>
using namespace std;
struct ListNode
{
int val;
ListNode *next;
ListNode() : val(0), next(NULL) {}
ListNode(int x) : val(x), next(NULL) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k) {
ListNode *p,*q,*dummy,*r,*cur,*tail;//tail为每一组的头标,颠倒后放在末尾作为下一组的头节点
int i=k,size=0,zu,n=0;
dummy= new ListNode(0,NULL);
p=head;q=head;
while(p){
p=p->next;
size++;
}
zu=size/k;
if(zu>=1){
while(i>0){
q=q->next;
i--;
}
}
else {
return head;
}
if(size==1){
return head;
}
p=head;cur=p;tail=p;
r=dummy;
while(zu>0){
zu--;n++;
while(p!=q){
cur=p;
p=p->next;
cur->next=r->next;
r->next=cur;
}//结束后p在下一组首位
i=k;
if(zu>0)
while(i>0&&q){
q=q->next;
i--;
}
r=tail;
tail=p;
}
if(tail){
r=tail;
}else{
//r=dummy;
r=NULL;
}
tail=dummy;
while(tail->next){
tail=tail->next;
}
tail->next=r;
return dummy->next;
}
};
ListNode *createByTail()
{
ListNode *head;
ListNode *p1,*p2;
int n=0,num;
int len;
cin>>len;
head=NULL;
while(n<len && cin>>num)
{
p1=new ListNode(num);
n=n+1;
if(n==1)
head=p1;
else
p2->next=p1;
p2=p1;
}
return head;
}
void displayLink(ListNode *head)
{
ListNode *p;
p=head;
cout<<"head-->";
while(p!= NULL)
{
cout<<p->val<<"-->";
p=p->next;
}
cout<<"tail\n";
}
int main()
{
int k;
ListNode* head = createByTail();
cin>>k;
head=Solution().reverseKGroup(head,k);
displayLink(head);
return 0;
}