顺序栈基本运算(实验题3.1)

来源:互联网 发布:淘宝店铺如何下架宝贝 编辑:程序博客网 时间:2024/05/16 10:18
////SqStack.h//顺序栈的基本运算//2013-10-12 0:06//#pragma once#define MaxSize 5typedef int ElemType;typedef struct{ElemType elem[MaxSize];int top;  //栈指针}SqStack;void InitStack(SqStack* &s);void ClearStack(SqStack* &s);int StackLength(SqStack* s);int StackEmpty(SqStack* s);int Push(SqStack* &s,ElemType e);  //进栈int Pop(SqStack* &s,ElemType& e);  //出栈int GetTop(SqStack* &s,ElemType& e);  //取栈顶元素void DispStack(SqStack* s);

//SqStack.cpp#include "SqStack.h"#include <malloc.h>#include <stdio.h>void InitStack( SqStack* &s ){s = (SqStack*)malloc(sizeof(SqStack));s->top = -1;}void ClearStack( SqStack* &s ){free(s);}int StackLength( SqStack* s ){return s->top+1;}int StackEmpty( SqStack* s ){return s->top == -1;}int Push( SqStack* &s,ElemType e ){if ( s->top >= MaxSize -1){return 0;}s->top ++;s->elem[s->top] = e;return 1;}int Pop( SqStack* &s,ElemType& e ){if ( -1 == s->top){return 0;}s->top--;return 1;}int GetTop( SqStack* &s,ElemType& e ){if ( s->top == -1 || s->top >= MaxSize){return 0;}e = s->elem[s->top];return 1;}void DispStack( SqStack* s ){if ( s->top == -1 || s->top >= MaxSize){return;}for ( int i = s->top; i >= 0; i --){printf("%d,",s->elem[i]);}printf("\n");}


 

 

main.cpp

#include "SqStack.h"int main(){SqStack*s;InitStack(s);Push(s,1);DispStack(s);Push(s,2);DispStack(s);Push(s,3);DispStack(s);Push(s,4);DispStack(s);ElemType e;Pop(s,e);DispStack(s);return 0;}