# 队列组合(栈和队列)

设计算法以求解从集合{1..n}中选取kk<=n）个元素的所有组合。例如，从集合{1..4}中选取2个元素的所有组合的输出结果为：1  21  31  42  3 2  43  4

1 2 3 4

1 2

1 3

1 4

2 3

2 4

3 4

``1 2 3``

``````1 2
1 3
2 3``````

``````#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct SqStack
{
int *base;
int *top;
int stacksize;
};
struct SqStack *initemptyStack(int m)
{
struct SqStack *s;
s=(struct SqStack*)malloc(sizeof(struct SqStack));
if(s!=NULL)
{
s->base=(int*)malloc(m);
if(s->base!=NULL)
{
s->top=s->base;
s->stacksize=m;
return s;
}
else
free(s);
}
return NULL;
}
int push(struct SqStack *s,int ch)
{
if(s->top-s->base<s->stacksize)
{
*(s->top)=ch;
s->top++;
return 1;
}
else
return 0;
}
int pops(struct SqStack *s,int *x)
{
if(s->top==s->base)
return 0;
else
*x=*(--s->top);
return 1;
}
int pop(struct SqStack *p1)
{
int *p;
if(p1->top==p1->base)
return 0;
else
{
p=--p1->top;
printf("%d ",*p);
while(--p1->top)
{
printf("%d\n",*(p1->top));
if(p1->top==p1->base)
break;
printf("%d ",*p);
}
p1->top=p;
return 1;
}
}
int main()
{
struct SqStack *s,*p1;
int ch,c;
s=initemptyStack(100);
p1=initemptyStack(100);
while(scanf("%d",&ch)!=EOF)
{
push(s,ch);
}
while(pops(s,&c))
{
push(p1,c);
}
while(p1->top-1!=p1->base)
{
pop(p1);
}
return 0;
}``````

``````#include<iostream>
using namespace std;
int main()
{
int a[100];
int i=0,n;
char c;
while(cin>>n)
{
a[i++]=n;
if((c=getchar())=='\n')
break;
}
int j;
int k;
for(j=0;j<i;j++)
{
for(k=j+1;k<i;k++)
{
cout<<a[j]<<" "<<a[k]<<endl;

}
}
return 0;
}``````