Chinaunix首页 | 论坛 | 博客
  • 博客访问: 200993
  • 博文数量: 27
  • 博客积分: 1400
  • 博客等级: 上尉
  • 技术积分: 350
  • 用 户 组: 普通用户
  • 注册时间: 2009-10-22 08:34
文章分类

全部博文(27)

文章存档

2011年(1)

2010年(1)

2009年(25)

我的朋友

分类: C/C++

2009-10-22 16:39:29

今天看到一道题是用两个栈实现队列的操作,就编了这个程序,复习一下顺序栈的操作。用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;
}
阅读(1777) | 评论(0) | 转发(0) |
0

上一篇:vim常用配置(.vimrc)

下一篇:c笔试题

给主人留下些什么吧!~~