Implementation of sequential Stack
The data structure of the sequence stack is as follows:
Typedef struct {ElemType data [MaxSize]; // stack data int top; // stack top pointer} SqStack;
Implement the following functions:
Void InitStack (SqStack * & s); // initialize the stack void DestroyStack (SqStack * & s); // destroy the stack int StackLength (SqStack * s ); // calculate the stack length int StackEmpty (SqStack * s); // whether the stack is empty int Push (SqStack * & s, ElemType e ); // stack-In int Pop (SqStack * & s, ElemType & e); // stack-out int GetTop (SqStack * s, ElemType & e ); // obtain the top element of the stack void DispStack (SqStack * s); // output Stack
Specific implementation code:
# Include
# Include
# Include
# Define ElemType int # define MaxSize 1000 # define GET_ARRAY_LENGTH (array) (sizeof (array)/sizeof (array [0]) using namespace std; typedef struct {ElemType data [MaxSize]; // stack data int top; //} SqStack; void InitStack (SqStack * & s ); // initialize the stack void DestroyStack (SqStack * & s); // destroy the stack int StackLength (SqStack * s); // calculate the stack length int StackEmpty (SqStack * s ); // whether the stack is empty int Push (SqStack * & s, ElemType e); // int Pop (SqStack * & s, ElemType & e ); // output stack int GetTop (SqStack * s, ElemType & e); // obtain the top stack element void DispStack (SqStack * s ); // output stack void InitStack (SqStack * & s) {s = (SqStack *) malloc (sizeof (SqStack); s-> top =-1 ;} void DestroySqStack (SqStack * & s) {free (s);} int StackLength (SqStack * s) {return (s-> top + 1 );} int StackEmpty (SqStack * s) {return (s-> top =-1);} void DispStack (SqStack * s) {for (int I = s-> top; i>-1; I --) cout <
Data [I] <"; cout <
Top + 1 = MaxSize) return-1; else {s-> data [s-> top + 1] = e; s-> top ++; return 1 ;}} int Pop (SqStack * & s, ElemType & e) {if (s-> top =-1) return-1; else {e = s-> data [s-> top]; s-> top --; return 1 ;}} int GetTop (SqStack * s, ElemType & e) {if (s-> top =-1) return-1; else {e = s-> data [s-> top]; return 1 ;}} int main () {int I = 0; ElemType e; SqStack * s = NULL; ElemType a [] = {212,}; InitStack (s ); for (int I = 0; I
The code execution result is as follows: