通过一个循环队列重新排列栈中元素
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
/*设顺序栈S中有2n个元素,从栈顶到栈底的元素依次为a2n,a2n-1,...,a1,要求通过一个循环队列
重新排列栈中元素,使得从栈顶到栈底的元素依次为a2n,a2n-2,...,a4,a2,a2n-1,a2n-3,...,
a3,a1,请设计算法实现该操作,要求空间复杂度和时间复杂度均为O(n).*/
#include
#include
#define MAXSIZE 50
typedef struct
{
int data[MAXSIZE];
int top;
}SeqStack;
typedef struct
{
int data[MAXSIZE];
int front;
int rear;
}SeqQueue;
void Print(SeqStack *S,const n)
{
int i=0;
for(;i
printf("\n");
}
void SetStack(SeqStack *S,const int n)
{
int i=0;
int x;
S->top=-1;
printf("请输入数据元素:\n");
for(i=0;i
scanf("%d",&x);
S->top++;
S->data[S->top]=x;
// i++;
}
// Print(S,n);
}
int PopStack(SeqStack *S)
{
int x;
if(S->top<=MAXSIZE-1&&S->top>=0)
{
x=S->data[S->top];
S->top--;
return x;
}
else
exit(0);
}
void PushStack(SeqStack *S,int x)
{
if(S->top
// if(S->top
{
S->top++;
S->data[S->top]=x;
}
else
exit(0);
}
void SetQueue(SeqQueue *Q,SeqStack *S,const int n)
{
int i=0;
Q->front=0;
Q->rear=0;
for(i=0;i
Q->rear=(Q->rear+1)%MAXSIZE;
Q->data[Q->rear]=PopStack(S);
// i++;
}
// printf("\n==%d==\n",S->top);
}
int QueueEmpty(SeqQueue *Q)
{
if(Q->front==Q->rear)
return 1;
else
return 0;
}
int PopQueue(SeqQueue *Q)
{
int x;
if(!QueueEmpty(Q))
{
x=Q->data[Q->front+1];
Q->front=(Q->front+1)%MAXSIZE;
return x;
}
else
exit(0);
}
void AddQueue(SeqQueue *Q,int x)
{
Q->rear=(Q->rear+1)%MAXSIZE;
Q->data[Q->rear]=x;
}
void Fun(SeqQueue *Q,SeqStack *S,const int n)
{
int i=0;
int x=0;
for(;i
x=PopQueue(Q);
// printf("*(%d)*%d%d\n",x,i,n);
if(i%2==0)
{
PushStack(S,x);
// printf("XXC");
}
else
AddQueue(Q,x);
}
while(!QueueEmpty(Q))
{
x=PopQueue(Q);
PushStack(S,x);
}
}
/*
void Print(SeqStack *S,const n)
{
int i=0;
for(;i
}
void PrintQ(SeqQueue *Q,const n)
{
int i=1;
for(;i<=n;i++)
printf("%d ",Q->data[i]);
}*/
void main()
{
SeqStack *S;
SeqQueue *Q;
int n;
S=(SeqStack *)malloc(sizeof(SeqStack));
Q=(SeqQueue *)malloc(sizeof(SeqQueue));
printf("请输入数据个数(偶数个)\n");
scanf("%d",&n);
SetStack(S,n);
printf("初始结果为:\n");
Print(S,n);
SetQueue(Q,S,n);
// printf("\n");
// PrintQ(Q,n);
Fun(Q,S,n);
printf("转换后结果为:\n");
Print(S,n);
}