顺序栈的实现与顺序线性表类似,不过区别在于栈是一种受限的线性表,必须先进后出,本章我们来实现顺序栈的基本操作,关于链栈的基本操作,可看【链栈】——不带头结点,里面有详细代码
#includeusing namespace std; #define Maxsize 50 typedef struct { int data[Maxsize]; int top; }Sqstack; void Initstack(Sqstack& S) //初始化 { S.top = -1; } bool Emptystack(Sqstack S) //判空 { if (S.top == -1) return true; else return false; } bool Push(Sqstack& S, int e) //进栈 { if (S.top >= Maxsize) return false; else { S.data[++S.top] = e; } return true; } bool Pop(Sqstack& S, int &e) //出栈 { if (S.top == -1) return false; else { e = S.data[S.top--]; } return true; } bool Gettop(Sqstack S, int& e) { if (S.top == -1) return false; else e = S.data[S.top]; return true; } int main() { Sqstack S; Initstack(S); cout << Emptystack(S) << endl; Push(S, 1); Push(S, 2); Push(S, 3); int e = 0; Gettop(S, e); cout << e << endl; cout << endl; cout << Emptystack(S) << endl; return 0; }



