题目
解答
#include<stdio.h>
#include <stdlib.h>
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
typedef struct{
int *base;
int *top;
int stacksize;
}SqStack;
int InitStack_Sq(SqStack *S){
(*S).base = (int *)malloc(STACK_INIT_SIZE*sizeof(int));
if(!(*S).base)
exit(0);
(*S).top = (*S).base;
(*S).stacksize = STACK_INIT_SIZE;
return 1;
}
int StackEmpty_Sq(SqStack S){
if(S.top==S.base)
return 1;
else
return 0;
}
int Push_Sq(SqStack *S, int e){
if((*S).top-(*S).base>=(*S).stacksize){
(*S).base = (int *)realloc((*S).base, ((*S).stacksize+STACKINCREMENT)*sizeof(int));
if(!(*S).base)
exit(0);
(*S).top = (*S).base + (*S).stacksize;
(*S).stacksize += STACKINCREMENT;
}
*(S->top) = e;
(S->top)++;
return 1;
}
int Pop_Sq(SqStack *S, int *e){
if((*S).top==(*S).base)
return 0;
(*S).top--;
*e = *((*S).top);
return 1;
}
void StackTraverse_Sq(SqStack S){
int *p = S.base;
while(p<S.top)
printf("%d ", *p++);
printf("\n");
}
void EnQueue(SqStack *S1, int e){
Push_Sq(S1, e);
}
int DeQueue(SqStack *S1, SqStack *S2){
int e, tmp;
if(StackEmpty_Sq(*S1))
exit(0);
if(!StackEmpty_Sq(*S2))
Pop_Sq(S2, &e);
else{
while(!StackEmpty_Sq(*S1)){
Pop_Sq(S1, &tmp);
Push_Sq(S2, tmp);
}
Pop_Sq(S2, &e);
}
return e;
}
int main(){
SqStack S1, S2;
int i;
printf("初始化顺序栈S1、S2 ...\n");
InitStack_Sq(&S1);
InitStack_Sq(&S2);
for(i=1; i<=6; i++){
printf("将 \"%2d\" 入模拟队 S1 ", 2*i);
EnQueue(&S1, 2*i);
printf("(累计第 %d 个元素)...\n", S1.top-S1.base);
}
printf("顺序栈S1中的元素为:\n");
StackTraverse_Sq(S1);
printf("顺序栈S2中的元素为:\n");
StackTraverse_Sq(S2);
printf("用S1和S2模拟队列...\n");
printf("队头元素 %d 出队列\n", DeQueue(&S1, &S2));
printf("顺序栈S1中的元素为:\n");
StackTraverse_Sq(S1);
printf("顺序栈S2中的元素为:\n");
StackTraverse_Sq(S2);
return 0;
}