今天看到一道题是用两个栈实现队列的操作,就编了这个程序,复习一下顺序栈的操作。用c语言实现。源代码如下:
/*
* Copyright (c) 2009-~ Hu bin
*
* This source code is released for free distribution under the terms of the
* GNU General Public License
*
* Author: Hu Bin
* Created Time: 2009年10月22日 星期四 09时25分10秒
* File Name: stack.c
*
* Description:
*/
#include
#include
#include
#include
#define MAXSIZE 100
typedef char DataType;
typedef struct
{
DataType data[MAXSIZE];
int top;
}SqStack;
void StackInit(SqStack *S) /*初始化顺序栈*/
{
S->top=-1;
}
int StackIsEmpty(SqStack *S) /*判断栈是否为空*/
{
if(S->top == -1)
return 1;
else
return 0;
}
int StackIsFull(SqStack *S) /*判断栈是否为满*/
{
if(S->top==MAXSIZE)
return 1;
else
return 0;
}
void StackPush(SqStack *S,DataType dat) /*入栈*/
{
if(StackIsFull(S)) {
printf("The Stack Is Full!\n");
exit(1);
}
S->data[++S->top]=dat;
}
DataType StackPop(SqStack *S) /*出栈*/
{
DataType dat;
if(StackIsEmpty(S)){
printf("The Stack Is Empty!\n");
exit(1);
}
dat=S->data[S->top];
S->top--;
return dat;
}
void StackDisplay(SqStack *S) /*打印栈里元素*/
{
int top1;
DataType dat;
if(StackIsEmpty(S)){
printf("The Stack Is Empty!\n");
exit(1);
}
top1=S->top;
while(S->top > -1){
dat=S->data[S->top];
printf("%c",dat);
S->top--;
}
S->top=top1;
printf("\n");
}
int main(int args,char *argv[])
{
SqStack *S,*Q;
DataType dat,tmp1,tmp2;
int len,i;
S=(SqStack *)malloc(sizeof(SqStack)); /*给栈分配空间*/
Q=(SqStack *)malloc(sizeof(SqStack));
StackInit(S);
StackInit(Q);
len=26;
i=0;
printf("Input Queue!\n"); /*把A-Z放过S栈中*/
while(i dat='A'+i;
StackPush(S,dat);
printf("%c",dat);
i++;
}
printf("\n");
printf("After Input Queue!\n");
StackDisplay(S); /*打印S栈的元素*/
while((StackIsEmpty(S)) != 1) {
dat=StackPop(S); /*S栈的不断出栈*/
StackPush(Q,dat); /*将S栈中出栈的元素入栈到栈Q中*/
}
printf("Output Queue!\n");
while((StackIsEmpty(Q)) != 1) {
dat=StackPop(Q); /*Q栈出栈,实现队列*/
printf("%c",dat);
}
printf("\n");
return 0;
}
阅读(1831) | 评论(0) | 转发(0) |