数据结构——栈(顺序栈)

来源:互联网 发布:淘宝天猫投诉电话人工 编辑:程序博客网 时间:2024/05/16 23:53

问题及代码

编写一个程序,实现顺序栈(假设栈中元素类型为char)的各种基本运算,并在此基础上完成以下功能

(1)初始化栈s;

(2)判断栈s是否非空;

(3)依次进栈元素a,b,c,d,e;

(4)判断栈s是否非空;

(5)输出栈长度;

(6)输出从栈顶到栈底元素;

(7)输出出栈序列;

(8)判断栈s是否非空;

(9)释放栈;

代码

#include <iostream>#include <malloc.h>#include <stdio.h>using namespace std;#define MaxSize 100typedef char ElemType;typedef struct{    ElemType data[MaxSize];    int top;} SqStack;//初始化栈void InitStack(SqStack *&s){    s=(SqStack*)malloc(sizeof(SqStack));    s->top=-1;}//判断栈是否为空bool StackEmpty(SqStack *&s){    return(s->top==-1);}//进栈bool Push(SqStack *&s,ElemType e){    if(s->top==MaxSize-1)        return false;    s->top++;    s->data[s->top]=e;    return true;}//计算栈长度int  StackLength(SqStack *&s){    int i=0;    int n=s->top;    while(n!=-1)    {        i++;        n--;    }    return i;}//输出从栈顶到栈底元素void Print(SqStack *&s){    int n=s->top;    while(n!=-1)    {        printf("%c ",s->data[n]);        n--;    }    printf("\n");}//出栈void Pop(SqStack *&s){    while(s->top!=-1)    {        printf("%c ",s->data[s->top]);        s->top--;    }    printf("\n");}int main(){    SqStack *s;    printf("(1)初始化栈\n");    InitStack(s);    if(StackEmpty(s))        printf("(2)栈为空\n");    else printf("(2)栈为非空\n");    printf("(3)依次进栈元素a,b,c,d,e\n");    Push(s,'a');    Push(s,'b');    Push(s,'c');    Push(s,'d');    Push(s,'e');    if(StackEmpty(s))        printf("(4)栈为空\n");    else printf("(4)栈为非空\n");    printf("(5)栈的长度为:%d\n", StackLength(s));    printf("(6)输出从栈顶到栈底元素:");    Print(s);    printf("(7)输出出栈序列:");    Pop(s);    if(StackEmpty(s))        printf("(8)栈为空\n");    else printf("(8)栈为非空\n");    printf("(9)释放栈");    free(s);    return 0;}
运算结果


原创粉丝点击