1. 顺序栈
#include <iostream>
using namespace std;
#define MAXSIZE 12
#define OK 1
#define ERROR 0
typedef struct Sqstack {
int* top;
int* base;
int stacksize;
}Sqstack;
int initSatck(Sqstack& s) {
s.base = new int[MAXSIZE];
if (!s.base) exit(0);
s.top = s.base;
s.stacksize = MAXSIZE;
return OK;
}
int Push(Sqstack& s, int e) {
if (s.top - s.base == MAXSIZE) return 0;
*s.top++ = e;
return OK;
}
int Pop(Sqstack& s, int& e) {
if (s.top == s.base) return ERROR;
e = *(--s.top);
return OK
}
int getTop(Sqstack& s) {
if (s.top!=s.base) {
return *(s.top - 1);
}
}
void deleteStack(Sqstack &s) {
delete[] s.base;
cout << "成功删除";
}
void printStack(Sqstack& s) {
for (int i = 0; i < 12; i++) {
cout << s.base[i] << " ";
}
}
int main() {
Sqstack s;
initSatck(s);
for (int i = 0; i < 12; i++) {
Push(s, i);
}
int flag = Push(s, 13);
if (flag==0) {
cout << "栈已满";
}
printStack(s);
deleteStack(s);
return 0;
}
2.链栈
#include <iostream>
using namespace std;
#define ERROR 0
#define OK 1
typedef struct stackNode {
int data;
struct stackNode* next;
}stackNode,*linkStack;
int initStack(linkStack &S) {
S = NULL;
return OK;
}
int Push(linkStack& S, int e) {
linkStack p = new stackNode;
p->data = e;
p->next = S;
S = p;
return OK;
}
int Pop(linkStack& S, int &e) {
if (S = NULL) return ERROR;
e = S->data;
linkStack p = S;
S = S->next;
delete p;
return OK;
}
int getTop(linkStack& S) {
if (S!=NULL) {
return S->data;
}
}