实现从一个队列创建一个栈,使队头为栈底,队尾为栈顶,算法最后要求使队列为空队,并输出栈中的元素。
#include <cstdlib>
#include <iostream>
#include <queue>
using namespace std;
#include <stdio.h>
#include <stdlib.h>
enum { MAXNUM = 20
};
typedef int DataType;
struct SeqStack {
int t;
DataType s[MAXNUM];
};
typedef struct SeqStack *PSeqStack;
PSeqStack createEmptyStack_seq( void ) {
PSeqStack pastack = (PSeqStack)malloc(sizeof(struct SeqStack));
if (pastack==NULL)
printf("Out of space!! \n");
else
pastack->t = -1;
return pastack;
}
int isEmptyStack_seq(PSeqStack pastack) {
if(pastack->t==NULL)
return 0;
else
return 1;
}
void push_seq(PSeqStack pastack, DataType x ) {
if( pastack->t >= MAXNUM - 1 )
printf( "Stack Overflow! \n" );
else {
pastack->t++;
pastack->s[pastack->t] = x;
}
}
void pop_seq( PSeqStack pastack ) {
if (pastack->t == -1 )
printf( "Underflow!\n" );
else
pastack->t--;
}
int StackTop(PSeqStack S,DataType *d)
{
if(S->t<=-1)
{
printf("堆栈已空!\n");
return 0;
}
else
{
* d=S->s[S->t];
return 1;
}
}
DataType top_seq(PSeqStack pastack ) {
return pastack->s[pastack->t];
}
int main()
{
int e,n,m,p;
queue<int> q1;
printf("初始化队列\n");
PSeqStack A;
int l=0,i;
A=createEmptyStack_seq();
printf("初始化栈\n");
printf("请输入队列的元素个数:\n");
scanf("%d",&n);
if(!q1.empty())
cout<<"队列不空\n";
while(n>0)
{
scanf("%d",&p);
q1.push(p);
n--;
}
printf("队列个数为:\n");
n=q1.size();
cout<<n<<endl;
printf("队列最后一位数为:\n");
m=q1.back();
cout<<m<<endl;
printf("队列元素分别为:\n");
for(int j=0;j<n;j++)
{
e=q1.front();
push_seq(A, e);
cout<<e<<" ";
q1.pop();
}
cout<<endl;
if(q1.empty())
cout<<"队列为空"<<endl;
else
cout<<"队列不空"<<endl;
system("PAUSE");
printf("输出栈元素\n");
while(n!=0)
{
l++;
printf("此时栈顶元素为:");
StackTop(A,&i);
printf("%d\n",i);
pop_seq(A);
n--;
}
printf("栈元素个数为:%d\n",l);
return 0;
}