第五周项目2-建立顺序栈算法库

来源:互联网 发布:中石油风险矩阵 编辑:程序博客网 时间:2024/06/18 17:57

问题及代码:

/*   Copyright (c)2016,烟台大学计算机与控制工程学院   All rights reserved.   文件名称:ysx.cpp   作 者:于苏显 完成日期:2016年11月3日   版 本 号:v1.0         问题描述:定义顺序栈存储结构,实现其基本运算,并完成测试。   输入描述:无   程序输出:测试数据   */      

sqstack.h

#include <stdio.h>#include <malloc.h>#define MaxSize 100typedef char ElemType;typedef struct{    ElemType data[MaxSize];    int top;                //栈指针} SqStack;                  //顺序栈类型定义void InitStack(SqStack *&s);    //初始化栈void DestroyStack(SqStack *&s);  //销毁栈bool StackEmpty(SqStack *s);     //栈是否为空int StackLength(SqStack *s);  //返回栈中元素个数——栈长度bool Push(SqStack *&s,ElemType e); //入栈bool Pop(SqStack *&s,ElemType &e); //出栈bool GetTop(SqStack *s,ElemType &e); //取栈顶数据元素void DispStack(SqStack *s);  //输出栈

sqstack.cpp

#include "sqstack.h"void InitStack(SqStack *&s){    s=(SqStack*)malloc(sizeof(SqStack));    s->top=-1;}void DestroyStack(SqStack *&s){    free(s);}bool StackEmpty(SqStack *s){    return(s->top==-1);}int StackLength(SqStack *s){    return(s->top+1);}bool Push(SqStack *&s,ElemType e){    if(s->top<MaxSize-1)    {        s->top++;        s->data[s->top]=e;        return true;    }    else return false;}bool Pop(SqStack *&s,ElemType &e){    if(s->top==-1)        return false;    else    {        e=s->data[s->top];        s->top--;    return true;    }}bool GetTop(SqStack *s,ElemType &e){    if(s->top==-1)        return false;    else    {        e=s->data[s->top];        return true;    }}void DispStack(SqStack *s){    for(int i=s->top;i>=0;i--)        printf("%c ",s->data[i]);    printf("\n");}

main.cpp

#include "sqstack.h"int main(){    ElemType e;    SqStack *s;    printf("      顺序栈算法库\n\n");    printf(" (1)  初始化顺序栈s\n");    InitStack(s);    printf(" (2)  顺序栈为%s\n",(StackEmpty(s)?"空":"非空"));    printf(" (3)  依次进顺序栈元素为k,k,e,v,o,l,i\n");    Push(s,'k');    Push(s,'k');    Push(s,'e');    Push(s,'v');    Push(s,'o');    Push(s,'l');    Push(s,'i');    printf(" (4)  顺序栈为%s\n",(StackEmpty(s)?"空":"非空"));    printf(" (5)  顺序栈长度:%d\n",StackLength(s));    printf(" (6)  从顺序栈顶到链栈底元素:");    DispStack(s);    Pop(s,e);    printf(" (7)  出顺序栈元素:%c\n",e);    printf(" (8)  出顺序栈序列:");    while (!StackEmpty(s))    {   Pop(s,e);        printf("%c ",e);    }    printf("\n (9)  顺序栈为%s\n",(StackEmpty(s)?"空":"非空"));    printf(" (10) 释放顺序栈\n");    DestroyStack(s);    return 0;}

运行结果:


知识点总结:建立顺序栈算法库。

学习心得:要注意出入栈顺序:先进后出,后进先出。

0 0