在探索计算机科学的海洋中,数据结构是支撑起程序架构的基石。它们不仅仅承载着信息,更决定了算法的效率和程序的性能。在众多数据结构中,栈和队列以其独特的操作方式和应用场景,成为了编程世界中不可或缺的元素。C语言,作为接近硬件的编程语言,其简洁与高效使得在该语言环境下实现数据结构变得尤为重要。本篇文章旨在通过C语言的镜头,清晰展示栈和队列的基本概念、特点及应用,带领读者理解这两种数据结构背后的逻辑,以及如何在实际编程中根据需求选择适合的数据结构,从而提升程序设计和问题解决的能力。
文章目录
- 栈
- 队列
- 栈和队列面试题
- 总结
一、栈
1.1栈的概念及结构
栈是一种特殊的线性表,只允许在固定的一端进行插入和删除元素操作。
进行数据插入和删除操作的一端称为栈顶,另一端称为栈底。栈中的数据元素遵守后进先出LIFO(Last In First Out)的原则。
压栈/入栈:栈的插入操作叫做进栈/压栈/入栈,入数据在栈顶。
出栈:栈的删除操作叫做出栈,出数据也在栈顶。
1.2栈的实现
栈一般可以使用数组或者链表实现,相对而言数组的结构实现更优一些。因为数组在尾上插入数据的代价比较小。
推荐使用单链表,链表头作为栈顶
Stack.h
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#include<assert.h>
typedef int STDataType;
typedef struct Stack
{
STDataType* a;
int top;
int capacity;
}ST;
void STInit(ST* ps);
void STDestroy(ST* ps);
//栈顶
void STPush(ST* ps, STDataType x);
void STPop(ST* ps);
STDataType STTop(ST* ps);
int STSize(ST* ps);
bool STEmpty(ST* ps);
Stack.c
#include"Stack.h"
void STInit(ST* ps)
{
assert(ps);
ps->a = NULL;
ps->top = 0;
ps->capacity = 0;
}
void STDestroy(ST* ps)
{
assert(ps);
free(ps->a);
ps->a = NULL;
ps->top = ps->capacity = 0;
}
//栈顶
void STPush(ST* ps, STDataType x)
{
assert(ps);
//满了,扩容
if (ps->top == ps->capacity)
{
int newcapcity = ps->capacity == 0 ? 4 : ps->capacity * 2;
STDataType* tmp = (STDataType*)realloc(ps->a, newcapcity * sizeof(STDataType));
if (tmp == NULL)
{
perror("realloc fail");
return;
}
ps->a = tmp;
ps->capacity = newcapcity;
}
ps->a[ps->top] = x;
ps->top++;
}
void STPop(ST* ps)
{
assert(ps);
assert(!STEmpty(ps));
ps->top--;
}
STDataType STTop(ST* ps)
{
assert(ps);
assert(!STEmpty(ps));
return ps->a[ps->top - 1];
}
int STSize(ST* ps)
{
assert(ps);
return ps->top;
}
bool STEmpty(ST* ps)
{
assert(ps);
return ps->top == 0;
}
top指向0代表指向栈顶元素的下一个,top指向-1代表指向栈顶元素,先放,再++
二、队列
2.1队列的概念及结构
队列是只允许在一端进行插入数据操作、在另一端进行删除数据操作的特殊线性表。
队列具有先进先出 FIFO(First In First Out)
入队列:进行插入操作的一端称为队尾
出队列:进行删除操作的一端称为队头
2.2队列的实现
队列也可用数组和链表的结构实现,使用链表的结构实现更优一些,因为如果使用数组的结构,出队列在数组头上出数据,效率会比较低。
选择单链表,单向,哨兵位可要可不要
Queue.h
#pragma once
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#include<assert.h>
typedef int QDataType;
typedef struct QueueNode
{
int val;
struct QueueNode* next;
}QNode;
//入队列
//void QueuePush(QNode** pphead,QNode** pptail);
//
//出队列
//void QueuePop(QNode** pphead,QNode** pptail);
//
typedef struct Queue
{
QNode* phead;
QNode* ptail;
int size;
}Queue;
void QueueInit(Queue* pq);
void QueueDestroy(Queue* pq);
//入队列
void QueuePush(Queue*pq,QDataType x);
//出队列
void QueuePop(Queue* pq);
//取对头和取队尾
QDataType QueueFront(Queue* pq);
QDataType QueueBack(Queue* pq);
bool QueueEmpty(Queue* pq);
int QueueSize(Queue* pq);
Queue.c
另外扩展了解一下,实际中有时还会使用一种队列叫循环队列。环形队列可以使用数组实现,也可以使用循环链表实现。
三、栈和队列面试题
3.1 编程题
(1)括号匹配问题。. - 力扣(LeetCode)
参考代码:
typedef char STDataType;
typedef struct Stack
{
STDataType* a;
int top;
int capacity;
}ST;
void STInit(ST* ps);
void STDestroy(ST* ps);
void STPush(ST* ps, STDataType x);
void STPop(ST* ps);
STDataType STTop(ST* ps);
bool STEmpty(ST* ps);
void STInit(ST* ps)
{
assert(ps);
ps->a = NULL;
ps->top = 0;
ps->capacity = 0;
}
void STDestroy(ST* ps)
{
assert(ps);
free(ps->a);
ps->a = NULL;
ps->top = ps->capacity = 0;
}
void STPush(ST* ps, STDataType x)
{
assert(ps);
//ˣ
if (ps->top == ps->capacity)
{
int newcapcity = ps->capacity == 0 ? 4 : ps->capacity * 2;
STDataType* tmp = (STDataType*)realloc(ps->a, newcapcity * sizeof (STDataType));
if (tmp == NULL)
{
perror("realloc fail");
return;
}
ps->a = tmp;
ps->capacity = newcapcity;
}
ps->a[ps->top] = x;
ps->top++;
}
void STPop(ST* ps)
{
assert(ps);
assert(!STEmpty(ps));
ps->top--;
}
STDataType STTop(ST* ps)
{
assert(ps);
assert(!STEmpty(ps));
return ps->a[ps->top - 1];
}
bool STEmpty(ST* ps)
{
assert(ps);
return ps->top == 0;
}
bool isValid(char* s) {
ST st;
STInit(&st);
while(*s)
{
if(*s=='['||*s=='('||*s=='{')
{
STPush(&st,*s);
}
else
{
//右括号比左括号多
if(STEmpty(&st))
{
STDestroy(&st);//防止内存泄漏
return false;
}
char top=STTop(&st);
STPop(&st);
//符号不匹配
if((*s==']' && top!='[')
|| (*s==')' && top!='(')
|| (*s=='}' && top!='{'))
{
STDestroy(&st);//防止内存泄漏
return false;
}
}
++s;
}
//左括号比右括号多,栈不为空
bool ret=STEmpty(&st);
STDestroy(&st);
return ret;
}
(2) 用队列实现栈。. - 力扣(LeetCode)
要考虑变量的生命周期
参考代码:
typedef int QDataType;
typedef struct QueueNode
{
int val;
struct QueueNode* next;
}QNode;
typedef struct Queue
{
QNode* phead;
QNode* ptail;
int size;
}Queue;
void QueueInit(Queue* pq);
void QueueDestroy(Queue* pq);
//入队列
void QueuePush(Queue*pq,QDataType x);
//出队列
void QueuePop(Queue* pq);
//取对头和取队尾
QDataType QueueFront(Queue* pq);
QDataType QueueBack(Queue* pq);
bool QueueEmpty(Queue* pq);
int QueueSize(Queue* pq);
void QueueInit(Queue* pq)
{
assert(pq);
pq->phead = NULL;
pq->ptail = NULL;
pq->size = 0;
}
void QueueDestroy(Queue* pq)
{
assert(pq);
QNode* cur = pq->phead;
while (cur)
{
QNode* next = cur->next;
free(cur);
cur = next;
}
pq->phead = pq->ptail = NULL;
pq->size = 0;
}
// 入队列
void QueuePush(Queue* pq, QDataType x)
{
assert(pq);
QNode* newnode = (QNode*)malloc(sizeof(QNode));
if (newnode == NULL)
{
perror("malloc fail");
return;
}
newnode->val = x;
newnode->next = NULL;
if (pq->ptail)
{
pq->ptail->next = newnode;
pq->ptail = newnode;
}
else
{
pq->phead = pq->ptail = newnode;
}
pq->size++;
}
// 出队列
void QueuePop(Queue* pq)
{
assert(pq);
// 0个节点
// 温柔检查
//if (pq->phead == NULL)
// return;
// 暴力检查
assert(pq->phead != NULL);
// 一个节点
// 多个节点
if (pq->phead->next == NULL)
{
free(pq->phead);
pq->phead = pq->ptail = NULL;
}
else
{
QNode* next = pq->phead->next;
free(pq->phead);
pq->phead = next;
}
pq->size--;
}
QDataType QueueFront(Queue* pq)
{
assert(pq);
// 暴力检查
assert(pq->phead != NULL);
return pq->phead->val;
}
QDataType QueueBack(Queue* pq)
{
assert(pq);
// 暴力检查
assert(pq->ptail != NULL);
return pq->ptail->val;
}
bool QueueEmpty(Queue* pq)
{
assert(pq);
return pq->size == 0;
}
int QueueSize(Queue* pq)
{
assert(pq);
return pq->size;
}
typedef struct {
Queue q1;
Queue q2;
} MyStack;
MyStack* myStackCreate() {
MyStack* pst=(MyStack*)malloc(sizeof(MyStack));//建在堆上
QueueInit(&pst->q1);
QueueInit(&pst->q2);
return pst;
}
void myStackPush(MyStack* obj, int x) {
if(!QueueEmpty(&obj->q1))
{
QueuePush(&obj->q1,x);
}
else
{
QueuePush(&obj->q2,x);
}
}
int myStackPop(MyStack* obj) {
//不为空的前N-1个数据导入另一个队列,删掉最后一个数据
Queue* pEmptyQ=&obj->q1;
Queue* pNonEmptyQ=&obj->q2;
if(!QueueEmpty(&obj->q1))
{
pEmptyQ=&obj->q2;
pNonEmptyQ=&obj->q1;
}
//把不为空的前N-1个数据导入另一个空队列
while(QueueSize(pNonEmptyQ)>1)
{
int front=QueueFront(pNonEmptyQ);
QueuePush(pEmptyQ,front);
QueuePop(pNonEmptyQ);
}
int front=QueueFront(pNonEmptyQ);
QueuePop(pNonEmptyQ);
return front;
}
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) {
QueueDestroy(&obj->q1);
QueueDestroy(&obj->q2);
free(obj);
}
/**
* Your MyStack struct will be instantiated and called as such:
* MyStack* obj = myStackCreate();
* myStackPush(obj, x);
* int param_2 = myStackPop(obj);
* int param_3 = myStackTop(obj);
* bool param_4 = myStackEmpty(obj);
* myStackFree(obj);
*/
(3)用栈实现队列。. - 力扣(LeetCode)
参考代码:
typedef int STDataType;
typedef struct Stack
{
STDataType* a;
int top;
int capacity;
}ST;
void STInit(ST* ps);
void STDestroy(ST* ps);
void STPush(ST* ps, STDataType x);
void STPop(ST* ps);
STDataType STTop(ST* ps);
int STSize(ST* ps);
bool STEmpty(ST* ps);
void STInit(ST* ps)
{
assert(ps);
ps->a = NULL;
ps->top = 0;
ps->capacity = 0;
}
void STDestroy(ST* ps)
{
assert(ps);
free(ps->a);
ps->a = NULL;
ps->top = ps->capacity = 0;
}
//ջ
void STPush(ST* ps, STDataType x)
{
assert(ps);
//ˣ
if (ps->top == ps->capacity)
{
int newcapcity = ps->capacity == 0 ? 4 : ps->capacity * 2;
STDataType* tmp = (STDataType*)realloc(ps->a, newcapcity * sizeof(STDataType));
if (tmp == NULL)
{
perror("realloc fail");
return;
}
ps->a = tmp;
ps->capacity = newcapcity;
}
ps->a[ps->top] = x;
ps->top++;
}
void STPop(ST* ps)
{
assert(ps);
assert(!STEmpty(ps));
ps->top--;
}
STDataType STTop(ST* ps)
{
assert(ps);
assert(!STEmpty(ps));
return ps->a[ps->top - 1];
}
int STSize(ST* ps)
{
assert(ps);
return ps->top;
}
bool STEmpty(ST* ps)
{
assert(ps);
return ps->top == 0;
}
typedef struct {
ST pushst;
ST popst;
} MyQueue;
MyQueue* myQueueCreate() {
MyQueue* obj=malloc(sizeof(MyQueue));
STInit(&obj->pushst);
STInit(&obj->popst);
return obj;
}
void myQueuePush(MyQueue* obj, int x) {
STPush(&obj->pushst,x);
}
int myQueuePeek(MyQueue* obj) {
if(STEmpty(&obj->popst))
{
//pushst的数据导入popst
while(!STEmpty(&obj->pushst))
{
int top=STTop(&obj->pushst);
STPush(&obj->popst,top);//->
STPop(&obj->pushst);//交换这两句,不影响
}
}
return STTop(&obj->popst);
}//返回队头数据
int myQueuePop(MyQueue* obj) {
int front = myQueuePeek(obj);
STPop(&obj->popst);
return front;
}
bool myQueueEmpty(MyQueue* obj) {
return STEmpty(&obj->pushst) && STEmpty(&obj->popst);
}
void myQueueFree(MyQueue* obj) {
STDestroy(&obj->pushst);
STDestroy(&obj->popst);
free(obj);
}
/**
* Your MyQueue struct will be instantiated and called as such:
* MyQueue* obj = myQueueCreate();
* myQueuePush(obj, x);
* int param_2 = myQueuePop(obj);
* int param_3 = myQueuePeek(obj);
* bool param_4 = myQueueEmpty(obj);
* myQueueFree(obj);
*/
错误示例:
(4)设计循环队列。. - 力扣(LeetCode)
链表写起来并不容易,使用数组方便一些
参考代码:
typedef struct {
int* a;
int front;//指向头
int rear;//指向尾的下一个
int k;
} MyCircularQueue;
MyCircularQueue* myCircularQueueCreate(int k) {
MyCircularQueue* obj =(MyCircularQueue*)malloc(sizeof(MyCircularQueue));
//多开一个解决假溢出问题
obj->a=malloc(sizeof(int)*(k+1));
obj->front=0;
obj->rear=0;
obj->k=k;
return obj;
}
bool myCircularQueueIsEmpty(MyCircularQueue* obj) {
return obj->front==obj->rear;
}
bool myCircularQueueIsFull(MyCircularQueue* obj) {
//int rearNext=obj->rear+1;
//if(rearNext==obj->k+1)
//rearNext=0;
//return rearNext==obj->front;
return (obj->rear+1)%(obj->k+1)==obj->front;
}
bool myCircularQueueEnQueue(MyCircularQueue* obj, int value) {
if(myCircularQueueIsFull(obj))
return false;
obj->a[obj->rear]=value;
obj->rear++;
obj->rear%=(obj->k+1);//取模处理,构成环形
return true;
}
bool myCircularQueueDeQueue(MyCircularQueue* obj) {
if(myCircularQueueIsEmpty(obj))
return false;
obj->front++;
obj->front%=(obj->k+1);
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
return obj->a[(obj->rear-1+obj->k+1)%(obj->k+1)];
}
void myCircularQueueFree(MyCircularQueue* obj) {
free(obj->a);
free(obj);
}
/**
* Your MyCircularQueue struct will be instantiated and called as such:
* MyCircularQueue* obj = myCircularQueueCreate(k);
* bool param_1 = myCircularQueueEnQueue(obj, value);
* bool param_2 = myCircularQueueDeQueue(obj);
* int param_3 = myCircularQueueFront(obj);
* int param_4 = myCircularQueueRear(obj);
* bool param_5 = myCircularQueueIsEmpty(obj);
* bool param_6 = myCircularQueueIsFull(obj);
* myCircularQueueFree(obj);
*/
3.2 概念选择题
3.【解析】循环队列中,由于入队时尾指针rear向前追赶头指针front;出队时头指针front向前追赶尾指针rear,造成队空和队满时头尾指针均相等。因此,无法通过条件front==rear来判别队列是“空”还是“满”。对于这个题目来说,经过一系列正常的入队与退队操作后,front=rear=99,此时,要么队列为空(元素个数为0),要么队列为满(元素个数为100),因此选项D正确。
5.【解析】循环队列是一种数据结构,用于解决普通队列在顺序存储方式下容易出现的"假溢出"现象。在循环队列中,队头指针(front)指向队头元素,队尾指针(rear)指向队尾元素的下一个位置。循环队列的长度为N,因此有效队列长度的计算公式为:(rear−front+N)%N
这个公式的含义是:
rear−front 计算的是从队尾指针到队头指针的距离。
因为队列是循环的,所以需要加上N以确保超出队列长度的部分能够循环回来。
取模运算(%N)确保结果在合法的队列长度范围内。
通过上述公式,可以准确计算出循环队列中的有效元素个数。
因此选项B正确。
总结
通过详细的介绍和示例,我们可以深刻理解栈和队列在数据存储和访问方式上的根本区别。栈的后进先出原则使其在解决函数调用、表达式求值等问题中表现突出,而队列的先进先出特性则让其在任务调度、消息处理等场景中发挥着关键作用。使用C语言实现这两种数据结构,不仅让我们更加了解它们的工作原理,还提供了实际操作的经验,增强了我们调试和解决问题的能力。正确的选择和使用栈或队列,能够显著影响程序的性能和可靠性。希望本文的内容能够帮助读者在今后的学习和工作中,更加灵活和有效地应用栈和队列,进而编写出更加高效的代码。