栈: 先进后出~
顺序栈
顺序栈和顺序表一样,受最大空间限制. 工作量大时应尽量用链栈.
#include<iostream>
using namespace std;
#define MaxSize 100
// 顺序栈
struct SqStack{
int data[MaxSize]; // 存放栈元素的数组
int top; // 栈顶 的下标
};
// 把e入栈
bool push(SqStack &s, int e){
// 栈已满
if (s.top == MaxSize - 1) return false;
s.top = s.top + 1;
s.data[s.top] = e;
return true;
}
bool pop(SqStack &s){
if (s.top == MaxSize - 1) return false;
s.top = s.top - 1;
return true;
}
void print(SqStack s){
cout << "打印栈..." << endl;
for (int i = s.top; i >= 0; i--){
cout << i << ":" << s.data[i] << endl;
}
}
bool getTop(SqStack s, int &e){
if (s.top == -1) return false;
e = s.data[s.top];
return true;
}
int main(){
SqStack s;
// 初始化栈顶
s.top = -1;
cout << "依次将1, 2, 3入栈" << endl;
push(s, 1);
push(s, 2);
push(s, 3);
print(s);
cout << "出栈" << endl;
pop(s);
print(s);
int e = 0;
cout << "获取栈顶" << endl;
getTop(s, e);
cout << e << endl;
return 0;
}
依次将1, 2, 3入栈
打印栈...
2:3
1:2
0:1
出栈
打印栈...
1:2
0:1
获取栈顶
2
Program ended with exit code: 0
链栈
链战是采用链式存储结构实现的栈. 通常栈链用单链表表示
#include<iostream>
using namespace std;
struct StackNode{
int data;
struct StackNode *next;
};
// 初始化链栈 注意,当链头为栈顶,push是头插法,当链尾为栈顶,push是尾插法
StackNode* initStackNode(){
// 头节点
StackNode *s;
s = (StackNode *)malloc(sizeof(StackNode));
s->data = -1;
s->next = NULL;
return s;
}
bool push(StackNode *s, int e){
// 把e入栈 用头插法
StackNode *p, *q = s;
p = (StackNode *)malloc(sizeof(StackNode));
p->data = e;
p->next = q->next;
q->next = p;
return true;
}
bool pop(StackNode *s){
// 把栈顶元素出栈, 即删除第一个节点
// 栈满
if (s == NULL) return false;
StackNode *p = s, *q = s->next;
p->next = q->next;
free(q);
return true;
}
void print(StackNode *s){
StackNode *p = s->next; // 跳过头节点
cout << "从栈顶打印..." << endl;
while(p != NULL){
cout << p->data << endl;
p = p->next;
}
}
bool getTop(StackNode *L, int &e){
// 空栈
if (L->next == NULL) return false;
e = L->next->data; // 链表第一个节点的data
return true;
}
int main(){
StackNode *s = initStackNode();
cout << "依次将1, 2, 3入栈" << endl;
push(s, 1);
push(s, 2);
push(s, 3);
print(s);
cout << "出栈" << endl;
pop(s);
print(s);
cout << "获取栈顶" << endl;
int item = 0;
getTop(s, item);
cout << item << endl;
return 0;
}
依次将1, 2, 3入栈
从栈顶打印...
3
2
1
出栈
从栈顶打印...
2
1
获取栈顶
2
Program ended with exit code: 0