栈
- 1. 顺序栈
- 2.链栈
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 1typedef 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;//修改栈顶指针为preturn 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;}}