详细说明:https://blog.csdn.net/qq_43643944/article/details/115281425
1、顺序栈
#include <iostream>
using namespace std;
const int MAX = 10;
typedef int ElemType;
struct SqStack {
ElemType data[MAX];//存放栈中元素
ElemType top;// 栈顶指针,指向栈顶元素
};
void InitStack(SqStack &S) {//初始化栈
S.top = -1;
}
bool push(SqStack &S, ElemType val) {//入栈
if (S.top == MAX - 1)
return false;
S.data[++S.top] = val;
return true;
}
bool pop(SqStack &S, ElemType &e) {//出栈
if (S.top == -1)
return false;
e = S.data[S.top--];
return true;
}
int main() {
SqStack S;
InitStack(S);
ElemType e;
push(S, 1);
push(S, 2);
push(S, 3);
push(S, 4);
push(S, 5);
cout << "遍历栈中元素:";
for (int i = S.top; i > -1; --i) {
cout << S.data[i] << " ";
}
cout << endl;
pop(S, e);
cout << "出栈元素为:" << e << endl;
cout << "遍历栈中元素:";
for (int i = S.top; i > -1; --i) {
cout << S.data[i] << " ";
}
return 0;
}
2、链栈
#include <iostream>
using namespace std;
typedef int ElemType;
typedef struct LNode {//链表节点
ElemType data;
struct LNode *next;
} LNode, *LinkList;
struct LinkStack { //链栈
LinkList top;//top指针,指向栈顶
int count;//计数器,统计栈内元素个数
};
bool InitStack(LinkStack &S) {//初始化链栈
S.top = NULL;
S.count = 0;
return true;
}
bool push(LinkStack &S, ElemType val) {//进栈
LNode *p = (LNode *) malloc(sizeof(LNode));
if (p == NULL)
return false;
p->data = val;
p->next = S.top;
S.top = p;
S.count++;
return true;
}
bool pop(LinkStack &S, ElemType &e) {//出栈
if (S.top == NULL)
return false;
e = S.top->data;
LNode *q = S.top;
S.top = S.top->next;
S.count--;
free(q);
return true;
}
int main() {
LinkStack S;
InitStack(S);
ElemType e;
push(S, 1);
push(S, 2);
push(S, 3);
push(S, 4);
push(S, 5);
LNode *p = S.top;
cout << "遍历栈中元素:";
while (p != NULL) {
cout << p->data << " ";
p = p->next;
}
cout << endl;
pop(S, e);
cout << "出栈元素为:" << e << endl;
cout << "遍历栈中元素:";
p = S.top;
while (p != NULL) {
cout << p->data << " ";
p = p->next;
}
return 0;
}