3.1 顺序栈
顺序栈的基本操作
const int maxn = 1e4 + 5;
typedef struct {
int data[maxn];
int top;
} SqStack;
void Print(SqStack s) {
for(int i = 0; i <= s.top; i++)
cout << s.data[i] << " ";
cout << endl;
}
void InitStack(SqStack &s) {
memset(s.data, 0, sizeof(s.data));
s.top = -1;
}
bool StackEmpty(SqStack s) {
return (s.top == -1);
}
bool Push(SqStack &s, int e) {
if(s.top == maxn - 1)
return false;
s.data[++s.top] = e;
return true;
}
bool Pop(SqStack &s, int &e) {
if(s.top == -1)
return false;
e = s.data[s.top--];
return true;
}
bool GetTop(SqStack s, int &e) {
if(s.top == -1)
return false;
e = s.data[s.top];
return true;
}
3.2 链式栈
链栈的基本操作
typedef struct linknode {
int data;
struct linknode * next;
} LinkStNode;
void Print(LinkStNode *s) {
LinkStNode *p = s ->next;
while(p) {
cout << (p->data) << " ";
p = p->next;
}
cout << endl;
}
void InitStack(LinkStNode * &s) {
s = new linknode;
s->next = NULL;
}
bool StackEmpty(LinkStNode *s) {
return !(s->next);
}
void Push(LinkStNode *&s, int e) {
LinkStNode *p = new linknode;
p->data = e;
p->next = s->next;
s->next = p;
}
bool Pop(LinkStNode *&s, int &e) {
if(StackEmpty(s))
return false;
e = s->next->data;
s->next = s->next->next;
return true;
}
bool GetTop(LinkStNode *s, int &e) {
if(StackEmpty(s))
return false;
e = s->next->data;
return true;
}
3.3 栈的应用
3.3.1 括号匹配
#include <bits/stdc++.h>
using namespace std;
const int maxn = 2e3 + 6;
char st[maxn];
int top, len;
string str;
bool run() {
for(int i = 0; i < len; i++) {
if(str[i] == '(')
st[++top] = '(';
else if(str[i] == ')') {
if(top == -1)
return false;
top--;
}
}
if(top != -1)
return false;
return true;
}
int main() {
// freopen("in.txt", "r", stdin);
cin >> str;
top = -1, len = str.length();
cout << (run() ? "YES" : "NO") << endl;
return 0;
}
3.4 循环队列
const int maxn = 1e2 + 5;
typedef struct Qnode {
int data[maxn];
int front, rear;
} SqQueue;
void InitQueue(SqQueue &q) {
q.front = q.rear = 0;
}
bool QueueEmpty(SqQueue q) {
return (q.rear == q.front);
}
bool enQueue(SqQueue &q, int e) {
if((q.rear + 1) % maxn == q.front)
return false;
q.data[q.rear] = e;
q.rear = (q.rear + 1) % maxn;
return true;
}
bool deQueue(SqQueue &q, int &e) {
if(q.rear == q.front)
return false;
e = q.data[q.front];
q.front = (q.front + 1) % maxn;
return true;
}
3.5 链队
typedef struct qnode {
int data;
struct qnode * next;
} LinkNode;
typedef struct { //队列
LinkNode * front; //队头
LinkNode * rear; //队尾
} LinkQueue;
void InitQueue(LinkQueue &q) {
q.front = q.rear = (LinkNode*)malloc(sizeof(LinkNode)); //建立空的头结点
q.front->next = NULL;
}
bool QueueEmpty(LinkQueue q) {
return (q.front == q.rear);
}
void enQueue(LinkQueue &q, int e) {
LinkNode *s = new qnode;
s->data = e;
s->next = NULL; //建立要插入的s节点
q.rear ->next = s; //插入到队尾
q.rear = s; //尾指针后移
}
bool deQueue(LinkQueue &q, int &e) {
if(q.rear == q.front)
return false; //空队
LinkNode *p = q.front ->next; //p指向要删除的节点
e = p->data;
q.front ->next = p->next; //删除
if(q.rear == p)
q.rear = q.front; //如果队列变空
return true;
}