【数据结构与算法C】利用两个栈S1S2模拟一个队列,用栈的基本操作实线EnQueue,DeQueue,QueueEmpty
入队列
Created with Raphaël 2.1.2
开始
S2为空
出S1入S2
入S1
yes
no
出队列
Created with Raphaël 2.1.2
开始
S2不为空
出S2
结束
出S1入S2
S2不为空
出S2
yes
no
yes
#include<stdio.h>
#include<stdlib.h>
#define STACKINITSIZE 100
#define STACKINCREMENT 10
#define TRUE 1
#define FALSE 0
typedef int bool ;
typedef struct {
char *base;
char *top;
int stacksize;
}SqStack;
int StackLength(SqStack S);
bool StackEmpty(SqStack S);
bool DestroyStack(SqStack *S);
bool InitStack(SqStack *S){
S->base = (char *)malloc (STACKINITSIZE * sizeof (SqStack));
if (S->base == NULL){
return FALSE;
}
S->top = S->base;
S->stacksize = STACKINITSIZE;
return TRUE;
}
bool GetTop(SqStack S,char *e){
if (S.top == S.base){
return FALSE;
}
*e = *(S.top - 1 );
return TRUE;
}
bool Push(SqStack *S,char e){
if (S->top - S->base >=S->stacksize){
S->base = (char *)realloc(S->base,(S->stacksize + STACKINCREMENT) * sizeof (SqStack));
if (S->base == NULL){
return FALSE;
}
S->top = S->base + S->stacksize;
}
*S->top ++ = e;
return TRUE;
}
bool Pop(SqStack *S,char *e){
if (S->top == S->base){
return FALSE;
}
*e = * -- S->top;
return TRUE;
}
bool EnQueue(SqStack *S1,SqStack *S2,char e){
char temp;
if (StackEmpty(*S2) == TRUE){
while (StackEmpty(*S1) == FALSE){
Pop(S1,&temp);
Push(S2,temp);
}
}
Push(S1,e);
return TRUE;
}
bool DeQueue(SqStack *S1,SqStack *S2,char *e){
char temp;
if (StackEmpty(*S2) == TRUE && StackEmpty(*S1) == TRUE){
return FALSE;
}
if (StackEmpty(*S2) == FALSE){
Pop(S2,e);
}
else {
while (StackEmpty(*S1) == FALSE){
Pop(S1,&temp);
Push(S2,temp);
}
Pop(S2,e);
}
return TRUE;
}
bool QueueEmpty(SqStack S1,SqStack S2){
if (StackEmpty(S1) == TRUE && StackEmpty(S2) == TRUE){
return TRUE;
}else
return FALSE;
}
int main(){
SqStack S1,S2;
char ch;
char temp;
printf ("顺序栈的基本操作\n" );
if (InitStack(&S1) == 1 && InitStack(&S2) == 1 ){
printf ("栈初始化成功\n" );
}
else {
printf ("初始化失败\n" );
return 1 ;
}
printf ("现在输入一串字符串,压入队列:" );
ch = getchar();
while (ch != '\n' && EnQueue(&S1,&S2,ch)){
ch = getchar();
}
while (QueueEmpty(S1,S2) == FALSE){
DeQueue(&S1,&S2,&temp);
printf ("%c\t" ,temp);
}
return 0 ;
}
int StackLength(SqStack S){
return (S.top - S.base);
}
bool DestroyStack(SqStack *S){
if (S->base == NULL)
return FALSE;
free (S->base);
return TRUE;
}
bool StackEmpty(SqStack S){
if (S.top == S.base){
return TRUE;
}
else {
return FALSE;
}
}