栈的关键在于先进后出 的思想
#include <iostream>
#include <stdlib.h>
using namespace std;
#define STACK_MAX_SIZE 100
typedef struct {
int * base;
int * top;
int stacksize;
} SqStack;
void InitStack ( SqStack * S) {
S- > base= new int [ STACK_MAX_SIZE] ;
if ( ! S- > base)
exit ( - 1 ) ;
S- > top= S- > base;
S- > stacksize= STACK_MAX_SIZE;
}
bool push ( SqStack * S, int val) {
if ( S- > top- S- > base== S- > stacksize) {
cout<< "栈满插入失败!" << endl;
return false ;
} else {
* S- > top++ = val;
return true ;
}
}
int pop ( SqStack * S) {
if ( S- > top== S- > base) {
cout<< "此时为空栈!" << endl;
exit ( 2 ) ;
}
return * -- S- > top;
}
int GetTop ( SqStack S) {
if ( S. top== S. base) {
cout<< "此时为空栈!" << endl;
exit ( 2 ) ;
} else {
return * ( S. top- 1 ) ;
}
}
bool IsEmpty ( SqStack S) {
if ( S. top== S. base) {
return true ;
} else {
return false ;
}
}
int main ( ) {
SqStack S;
InitStack ( & S) ;
push ( & S, 1 ) ;
push ( & S, 2 ) ;
bool status= IsEmpty ( S) ;
if ( status) {
cout<< "这是个空栈!" << endl;
} else {
cout<< "不是个空栈!" << endl;
}
cout<< pop ( & S) << endl;
cout<< GetTop ( S) << endl;
return 0 ;
}