栈和队列也是一种数据结构,和顺序表、链表一样,属于线性表,也就是说它们的逻辑结构是线性的。
看了上面的图示,是不是感觉栈和顺序表有点类似,都是挨着挨着往进存数据,但不同的是顺序表可以在任意位置插入和删除数据(虽然效率不同),但是栈只能在固定的一端进行该操作。
进行插入和删除的一端叫栈顶,另一端叫栈底。栈中的元素都遵循先进后出的原则。因为先进栈的在栈底,后进栈的在栈顶,所以出去的时候顺序就和入栈时相反了。(如图所示)
压栈 \ 入栈:往栈顶插入数据; 出栈:删除栈顶数据。
注意这里说的栈是数据结构,不要和操作系统内存区域划分中的栈搞混了。
经常有人将系统中的栈和数据结构中的栈搞混,下面我来简单区分一下两者。

操作系统中的栈里面放的是局部变量和函数形参等东西,而数据结构说的栈是储存在堆上的,因为它是动态开辟的数据。 在写递归调用、斐波那契数等函数时,有时会发生栈溢出的现象,是因为栈的空间较小,所以我们一般将其改成迭代的方式,或用栈将其改为循环解决。
栈一般用数组来实现,但空间节省要求高时用链表。
有人可能会问为什么不都用链表?链表不仅能节省空间,而且不用扩容,不是更好吗?
单次来说,链表效率确实比顺序表高一点,但是整体而言,顺序表的性能效率甚至要高于链表,这涉及CPU高速缓存命中率了。最关键的是顺序表可以用下标来访问,但是链表不行。因此这里最好用数组。
栈的实现代码与之前顺序表的很相似,而且它更为简单,因为栈遵循先进后出的原则,只能从栈顶插入删除数据,所以不存在头插头删和指定位置插入删除的操作。
代码如下:
- //Stack.h(头文件)
-
- #pragma once
-
- #include
- #include
- #include
- #include
- #include
-
- typedef int STDataType;
- typedef struct stack
- {
- STDataType* a;
- int top;
- int capacity;
- }ST;
-
- void StackInit(ST* ps);
- void StackDestory(ST* ps);
-
- void StackPush(ST* ps, STDataType x);
- void StackPop(ST* ps);
-
- bool StackEmpty(ST* ps);
- STDataType StackTop(ST* ps);
- int StackSize(ST* ps);
- //Stack.c (栈实现接口)
-
- #include"stack.h"
-
- void StackInit(ST* ps)
- {
- assert(ps);
- ps->a = NULL;
- ps->top = ps->capacity = 0;
- }
-
- void StackDestory(ST* ps)
- {
- assert(ps);
- free(ps->a);
- ps->a = NULL;
- ps->top = ps->capacity = 0;
- }
-
- void StackPush(ST* ps, STDataType x)
- {
- assert(ps);
- if (ps->top == ps->capacity)
- {
- int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
- STDataType* tmp = (STDataType*)realloc(ps->a, sizeof(STDataType) * newcapacity);
- if (tmp == NULL)
- {
- perror("malloc fail");
- exit(-1);
- }
- ps->a = tmp;
- ps->capacity = newcapacity;
- }
- ps->a[ps->top] = x;
- ps->top++;
- }
-
- bool StackEmpty(ST* ps)
- {
- assert(ps);
- return ps->top == 0;
- }
-
- void StackPop(ST* ps)
- {
- assert(ps);
- assert(!StackEmpty(ps));
- ps->top--;
- }
-
- STDataType StackTop(ST* ps)
- {
- assert(ps);
- assert(!StackEmpty(ps));
- return ps->a[ps->top - 1];
- }
-
- int StackSize(ST* ps)
- {
- assert(ps);
- return ps->top;
- }
- //test.c (测试函数)
-
- #include"stack.h"
-
- void Test1()
- {
- ST S;
- StackInit(&S);
-
- StackPush(&S, 1);
- StackPush(&S, 2);
- StackPush(&S, 3);
-
- STDataType top = StackTop(&S);
- int num = StackSize(&S);
-
- printf("%d ", StackTop(&S));
- StackPop(&S);
-
- StackPush(&S, 4);
- StackPush(&S, 5);
-
- while (!StackEmpty(&S))
- {
- printf("%d ", StackTop(&S));
- StackPop(&S);
- }
- printf("\n");
-
- StackDestory(&S);
- }
-
- int main()
- {
- Test1();
- return 0;
- }
来看一道编程题了解一下栈在实际中的作用。
力扣
https://leetcode.cn/problems/valid-parentheses/submissions/
这道题用刚刚所讲的栈的有关知识就可以轻松解决。
首先左右括号的匹配不仅仅是数个数,类似示例3这种类型不匹配的也是false。
解题思路:1、先写一个栈的实现函数,将其初始化。 2、用循环来遍历字符串中的每个字符,
如果是左括号 : ' { ' ' ( ' ' [ ' 就StackPush插入到栈顶,如果是右括号,就将栈顶字符弹出比较,如果匹配就删除栈顶字符并继续循环,直到结束或return false,不匹配直接return false。最后销毁。 3、大体思路是这样的,但还有很多细节上面没有考虑:如果字符串中没有右括号,就会不进入匹配条件,导致最后return true。需要在结尾判断栈是否为空,是return true,不是return false。
代码如下:(栈的实现上面写了,加到前面即可)
- bool isValid(char * s){
- ST P;
- StackInit(&P);
- while(*s)
- {
- if(*s == '{' || *s == '[' || *s == '(')
- {
- StackPush(&P,*s);
- }
- else
- {
- if(StackEmpty(&P))
- {
- StackDestory(&P);
- return false;
- }
- char top = StackTop(&P);
- StackPop(&P);
- if(*s != '}' && top == '{' ||
- *s != ']' && top == '[' ||
- *s != ')' && top == '(')
- return false;
- }
- ++s;
- }
- bool flag = StackEmpty(&P);
- StackDestory(&P);
- return flag;
- }
队列也是一种线性表,与栈只能在一端插入删除数据不同,队列是在一端插入数据,在另一端删除数据,遵循先进先出的原则。

队列的先进先出其实蛮符合我们的理解的,先来的先处理比较符合我们日常的逻辑。
所以队列的现实场景就可以用作抽号机系统。

队列的实现我们用链表,因为要在头部删除数据需要挪动数据,这就是比较麻烦的问题了,所以我们用链表实现。
这里我们用单链表实现,稍微节省一点空间。
代码如下:
- //Queue.h
-
- #pragma once
-
- #include
- #include
- #include
- #include
- #include
-
- typedef int QDataType;
- typedef struct QueueNode
- {
- struct QueueNode* next;
- QDataType data;
- }QNode;
-
- typedef struct Queue
- {
- QNode* head;
- QNode* tail;
- }Queue;
-
- void QueueInit(Queue* p);
- void QueueDestory(Queue* p);
- void QueuePush(Queue* p, QDataType x);
- void QueuePop(Queue* p);
- QDataType QueueFront(Queue* p);
- QDataType QueueBack(Queue* p);
- bool QueueEmpty(Queue* p);
- int QueueSize(Queue* p);
- //Queue.c
-
- #include"Queue.h"
-
- void QueueInit(Queue* p)
- {
- assert(p);
- p->head = p->tail = NULL;
- }
-
- void QueueDestory(Queue* p)
- {
- assert(p);
- QNode* cur = p->head;
- while (cur)
- {
- QNode* del = cur;
- cur = cur->next;
- free(del);
- }
- p->head = p->tail = NULL;
- }
-
- void QueuePush(Queue* p, QDataType x)
- {
- assert(p);
- QNode* newnode = (QNode*)malloc(sizeof(QNode));
- if (newnode == NULL)
- {
- perror("malloc fail");
- exit(-1);
- }
- else
- {
- newnode->next = NULL;
- newnode->data = x;
- }
- if (p->tail == NULL)
- {
- p->head = p->tail = newnode;
- }
- else
- {
- p->tail->next = newnode;
- p->tail = p->tail->next;
- }
- }
-
- void QueuePop(Queue* p)
- {
- assert(p);
- assert(!QueueEmpty(p));
- if (p->head->next == NULL)
- {
- free(p->head);
- p->head = p->tail = NULL;
- }
- else
- {
- QNode* del = p->head;
- p->head = p->head->next;
- free(del);
- }
- }
-
- QDataType QueueFront(Queue* p)
- {
- assert(p);
- assert(!QueueEmpty(p));
- return p->head->data;
- }
- QDataType QueueBack(Queue* p)
- {
- assert(p);
- assert(!QueueEmpty(p));
- return p->tail->data;
- }
-
- bool QueueEmpty(Queue* p)
- {
- assert(p);
- return p->head == NULL;
- }
- int QueueSize(Queue* p)
- {
- assert(p);
- int count = 0;
- QNode* cur = p->head;
- while (cur)
- {
- count++;
- cur = cur->next;
- }
- return count;
- }
- //test.c
-
- void Test2()
- {
- Queue S;
- QueueInit(&S);
- QueuePush(&S, 1);
- QueuePush(&S, 2);
- QueuePush(&S, 3);
- QueuePush(&S, 4);
-
- QueuePop(&S);
-
- QDataType front = QueueFront(&S);
- QDataType back = QueueBack(&S);
- int num = QueueSize(&S);
- QueueDestory(&S);
- }
CSDN
https://mp.csdn.net/mp_blog/creation/editor/126172201?spm=1000.2115.3001.4503
这道题要用两个队列实现栈,思路其实很简单,栈和队列处理数据的方式是相反的,栈是一端处理,先进后出;队列是两端处理,先进先出。
要想实现队列到栈的处理数据方式,就要用两个队列倒数据。用一个队列存储数据,另一个队列为空,需要取出或删除数据(对于栈来说是栈顶)就要将非空队列的数据倒入空队列,将非空队列的最后一个数据取出或删除即可。

代码如下:(先将之前写的队列实现函数放在OJ前面)
- typedef struct {
- Queue q1;
- Queue q2;
- } MyStack;
-
-
- MyStack* myStackCreate() {
- MyStack* obj = (MyStack*)malloc(sizeof(MyStack));
- QueueInit(&obj->q1);
- QueueInit(&obj->q2);
- return obj;
- }
-
- void myStackPush(MyStack* obj, int x) {
- if(!QueueEmpty(&obj->q1))
- {
- QueuePush(&obj->q1,x);
- }
- else
- {
- QueuePush(&obj->q2,x);
- }
- }
-
- int myStackPop(MyStack* obj) {
- Queue* empty = &obj->q1;
- Queue* nonempty = &obj->q2;
- if(!QueueEmpty(&obj->q1))
- {
- empty = &obj->q2;
- nonempty = &obj->q1;
- }
-
- while(QueueSize(nonempty) > 1)
- {
- QueuePush(empty,QueueFront(nonempty));
- QueuePop(nonempty);
- }
- int top = QueueFront(nonempty);
- QueuePop(nonempty);
- return top;
- }
-
- int myStackTop(MyStack* obj) {
- if(!QueueEmpty(&obj->q1))
- {
- return QueueBack(&obj->q1);
- }
- else
- {
- return QueueBack(&obj->q2);
- }
-
- }
-
- bool myStackEmpty(MyStack* obj) {
- return QueueEmpty(&obj->q1) && QueueEmpty(&obj->q2);
- }
-
- void myStackFree(MyStack* obj) {
- QueueDestory(&obj->q1);
- QueueDestory(&obj->q2);
-
- free(obj);
- obj = NULL;
- }
力扣
https://leetcode.cn/problems/implement-queue-using-stacks/
这道题和上一道刚好相反,是用两个栈实现队列。
大体思路是一致的,就是倒数据的顺序改变一下。

创建两个栈,push栈用来接收插入数据,pop栈用来取出或删除数据(栈中数据先进后出,push到pop中顺序逆置了)
代码如下:(栈的实现函数写在OJ前面)
- typedef struct {
- ST pushST;
- ST popST;
- } MyQueue;
-
-
- MyQueue* myQueueCreate() {
- MyQueue* obj = (MyQueue*)malloc(sizeof(MyQueue));
- StackInit(&obj->pushST);
- StackInit(&obj->popST);
- return obj;
- }
-
- void myQueuePush(MyQueue* obj, int x) {
- StackPush(&obj->pushST,x);
- }
-
- void myQueuePushToPop(MyQueue* obj){
- if(StackEmpty(&obj->popST))
- {
- while(!StackEmpty(&obj->pushST))
- {
- StackPush(&obj->popST,StackTop(&obj->pushST));
- StackPop(StackTop(&obj->pushST));
- }
- }
- }
- int myQueuePop(MyQueue* obj) {
- myQueuePushToPop(obj);
- int front = StackTop(&obj->popST);
- StackPop(StackTop(&obj->popST));
- return front;
- }
-
- int myQueuePeek(MyQueue* obj) {
- myQueuePushToPop(obj);
- int peekfront = StackTop(&obj->popST);
- return peekfront;
- }
-
- bool myQueueEmpty(MyQueue* obj) {
- return StackEmpty(&obj->pushST) && StackEmpty(&obj->popST);
- }
-
- void myQueueFree(MyQueue* obj) {
- StackDestory(&obj->pushST);
- StackDestory(&obj->popST);
- free(obj);
- }
力扣
https://leetcode.cn/problems/design-circular-queue/
设计一个循环队列,从逻辑结构上来说是环状的。


但物理结构还是线性表,还是队列。
这道题的关键在于判断队列的空与满,什么时候空,什么时候满。
给两个指针front与back,front指向头的位置(下标为0),尾指针back指向最后一个位置,这样设计就有一个缺陷。因为back始终是front的后一个,按上面设计的话,back在下标为0的位置时,front下标是-1,就会带来诸多不便和问题。
所以将back设计为最后一个位置的后一个。但是这样也还是有问题,因为是循环队列,back到最后一个位置时就跳回下标为0的位置了。此时就不好判断队列为空还是为满了,因为front == back 时,不能判断back是到最后一个位置了(队列满了)还是队列为空。
此时有两种解决思路:
一、增加一个size变量,用来记录队列中元素个数。这样就可以解决上面front==back的问题。
二、增加一个空间(可以存储数据),比如有5个元素,那就开6个空间,剩一个当作最后一个,也就是back的位置。
最后一个问题是用链表还是用数组,都可以,但是这里还是用数组更好一点,链表在细节处理上会有诸多问题。
代码如下:
- typedef struct {
- int* a;
- int front;
- int back;
- int N;//空间的大小
- } MyCircularQueue;
-
-
- MyCircularQueue* myCircularQueueCreate(int k) {
- MyCircularQueue* obj = (MyCircularQueue*)malloc(sizeof(MyCircularQueue));
- obj->a = (int*)malloc(sizeof(int)*(k+1));
- obj->front = obj->back = 0;
- obj->N = k+1;
- return obj;
- }
-
- bool myCircularQueueIsEmpty(MyCircularQueue* obj) {
- return obj->front == obj->back;
- }
-
- bool myCircularQueueIsFull(MyCircularQueue* obj) {
- return obj->front == ( (obj->back+1) % obj->N);
- }
-
- bool myCircularQueueEnQueue(MyCircularQueue* obj, int value) {
- if(!myCircularQueueIsFull(obj))
- {
- obj->a[obj->back] = value;
- obj->back++;
- //控制back到尾后回到下标为0的位置
- obj->back %= obj->N;
- return true;
- }
- else
- {
- return false;
- }
- }
-
- bool myCircularQueueDeQueue(MyCircularQueue* obj) {
- if(myCircularQueueIsEmpty(obj))
- return false;
- else
- {
- obj->front++;
- //控制front到尾后回到下标为0的位置
- obj->front %= obj->N;
- return true;
- }
- }
-
- int myCircularQueueFront(MyCircularQueue* obj) {
- if(myCircularQueueIsEmpty(obj))
- return -1;
- else
- return obj->a[obj->front];
- }
-
- int myCircularQueueRear(MyCircularQueue* obj) {
- if(myCircularQueueIsEmpty(obj))
- return -1;
- //else if(obj->back == 0)
- //{
- //return obj->a[obj->N-1];
- //}
- //else
- //{
- //return obj->a[obj->back-1];
- //}
- else
- {
- return obj->a[(obj->back-1+obj->N) % obj->N];
- }
- }
-
- void myCircularQueueFree(MyCircularQueue* obj) {
- free(obj->a);
- free(obj);
- }
栈和队列的基础讲解就到这里啦,感谢大家!!!