【数据结构】栈和队列(有完整的模拟实现代码!)

1、栈

1.1 栈的概念及结构

栈:一种特殊的线性表,其只允许在固定的一端进行插入和删除元素操作。进行数据插入和删除操作的一端称为栈顶,另一端称为栈底。栈中的数据元素遵守后进先出LIFO(Last In First Out)的原则。

压栈:栈的插入操作叫做进栈/压栈/入栈,入数据在栈顶

出栈:栈的删除操作叫做出栈。出数据也在栈顶

 1.2 栈的实现

栈的实现一般可以使用数组或者链表实现,相对而言数组的结构实现更优一些。因为数组在尾上插入数据的代价比较小。

1.2.1 Stack.h

#pragma once
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <stdbool.h>

typedef int STDataType;
typedef struct Stack
{
	STDataType* a;
	int top;//栈顶
	int capacity;//容量
}ST;

//初始化
void STInit(ST* pst);
//销毁
void STDestroy(ST* pst);
//入栈
void STPush(ST* pst, STDataType x);
//出栈
void STPop(ST* pst);
//获取栈顶元素
STDataType STTop(ST* pst);
//判断是否为空
bool STEmpty(ST* pst);
//获取栈中有效元素的个数
int STSize(ST* pst);

1.2.2 Stack.c

#define _CRT_SECURE_NO_WARNINGS 1
#include "Stack.h"

void STInit(ST* pst)
{
	assert(pst);

	pst->a = NULL;
	pst->top = 0;
	pst->capacity = 0;
}

void STDestroy(ST* pst)
{
	assert(pst);

	free(pst->a);
	pst->a = NULL;
	pst->top = 0;
	pst->capacity = 0;
}

void STPush(ST* pst, STDataType x)
{
	assert(pst);

	if (pst->top == pst->capacity)
	{
		int newcapacity = pst->capacity == 0 ? 4 : pst->capacity * 2;
		STDataType* tmp = (STDataType*)realloc(pst->a, newcapacity * sizeof(STDataType));
		if (NULL == tmp)
		{
			perror("realloc");
			return;
		}
		pst->a = tmp;
		pst->capacity = newcapacity;
	}

	pst->a[pst->top] = x;
	pst->top++;
}

void STPop(ST* pst)
{
	assert(pst);
	assert(!STEmpty(pst));

	pst->top--;
}

STDataType STTop(ST* pst)
{
	assert(pst);
	assert(!STEmpty(pst));

	return pst->a[pst->top - 1];
}

bool STEmpty(ST* pst)
{
	assert(pst);

	return pst->top == 0;
}

int STSize(ST* pst)
{
	assert(pst);

	return pst->top;
}

1.2.3 test.c

#define _CRT_SECURE_NO_WARNINGS 1
#include "Stack.h"

void TestStack1()
{
	ST st;
	STInit(&st);
	STPush(&st, 1);
	STPush(&st, 2);
	STPush(&st, 3);
	printf("%d\n", STTop(&st));
	STPop(&st);

	STPush(&st, 4);
	STPush(&st, 5);
	while (!STEmpty(&st))
	{
		printf("%d ", STTop(&st));
		STPop(&st);
	}
	STDestroy(&st);
}

int main()
{
	TestStack1();
	return 0;
}

2、队列

2.1 队列的概念及结构

队列:只允许在一端进行插入数据操作,在另一端进行删除数据操作的特殊线性表,队列具有先进先出FIFO(First In First Out) 的性质。

进行插入操作的一端称为队尾,进行删除操作的一端称为队头

2.2 队列的实现

队列也可以数组和链表的结构实现,使用链表的结构实现更优一些,因为如果使用数组的结构,出队列在数组头上出数据,效率会比较低。

2.2.1 Queue.h

#pragma once
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <stdbool.h>

typedef int QDataType;
typedef struct QueueNode
{
	QDataType data;
	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);
//获取队列中有效元素个数
int QueueSize(Queue* pq);
//检测队列是否为空
bool QueueEmpty(Queue* pq);

2.2.2 Queue.c

#define _CRT_SECURE_NO_WARNINGS 1
#include "Queue.h"

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 (NULL == newnode)
	{
		perror("malloc");
		return;
	}
	newnode->data = x;
	newnode->next = NULL;

	if (pq->phead == NULL)
	{
		pq->phead = pq->ptail = newnode;
	}
	else
	{
		pq->ptail->next = newnode;
		pq->ptail = newnode;
	}
	pq->size++;
}

void QueuePop(Queue* pq)
{
	assert(pq);
	assert(!QueueEmpty(pq));

	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(!QueueEmpty(pq));

	return pq->phead->data;
}

QDataType QueueBack(Queue* pq)
{
	assert(pq);
	assert(!QueueEmpty(pq));

	return pq->ptail->data;
}

int QueueSize(Queue* pq)
{
	assert(pq);

	return pq->size;
}

bool QueueEmpty(Queue* pq)
{
	assert(pq);

	return pq->size == 0;
}

test.c

#define _CRT_SECURE_NO_WARNINGS 1
#include "Queue.h"

void TestQueue()
{
	Queue q;
	QueueInit(&q);
	QueuePush(&q, 4);
	QueuePush(&q, 3);
	QueuePush(&q, 2);
	QueuePush(&q, 1);

	QueuePop(&q);
	while (!QueueEmpty(&q))
	{
		printf("%d ", QueueFront(&q));
		QueuePop(&q);
	}
	QueueDestroy(&q);
}

int main()
{
	TestQueue();
	return 0;
}

3、栈和队列练习题

3.1 括号匹配问题

20. 有效的括号 - 力扣(LeetCode)

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;
            }
            else
            {
                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;
}

3.2 用队列实现栈

225. 用队列实现栈 - 力扣(LeetCode)

typedef struct 
{
	Queue* q1;
	Queue* q2;
} MyStack;

MyStack* myStackCreate() 
{
	MyStack* obj = (MyStack*)malloc(sizeof(MyStack));
	obj->q1 = (Queue*)malloc(sizeof(Queue));
	obj->q2 = (Queue*)malloc(sizeof(Queue));

	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* pEmpty = obj->q1;
	Queue* pNonEmpty = obj->q2;
	if (!QueueEmpty(obj->q1))
	{
		pEmpty = obj->q2;
		pNonEmpty = obj->q1;
	}

	while (QueueSize(pNonEmpty) > 1)
	{
		QueuePush(pEmpty, QueueFront(pNonEmpty));
		QueuePop(pNonEmpty);
	}
	int top = QueueFront(pNonEmpty);
	QueuePop(pNonEmpty);

	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) 
{
	QueueDestroy(obj->q1);
	QueueDestroy(obj->q2);
	free(obj);
}

3.3 用栈实现队列

232. 用栈实现队列 - 力扣(LeetCode)

typedef struct
{
	ST pushst;
	ST popst;
}MyQueue;

MyQueue* myQueueCreate()
{
	MyQueue* obj = (MyQueue*)malloc(sizeof(MyQueue));
	if (obj == NULL)
	{
		perror("malloc fail");
		return NULL;
	}

	STInit(&obj->pushst);
	STInit(&obj->popst);

	return obj;
}

void myQueuePush(MyQueue* obj, int x)
{
	STPush(&obj->pushst, x);
}

int myQueuePop(MyQueue* obj)
{
	int front = myQueuePeek(obj);
	STPop(&obj->popst);
	return front;
}

int myQueuePeek(MyQueue* obj)
{
	if (STEmpty(&obj->popst))
	{
		while (!STEmpty(&obj->pushst))
		{
			STPush(&obj->popst, STTop(&obj->pushst));
			STPop(&obj->pushst);
		}
	}
	return STTop(&obj->popst);
}

bool myQueueEmpty(MyQueue* obj)
{
	return STEmpty(&obj->pushst) && STEmpty(&obj->popst);
}

void myQueueFree(MyQueue* obj)
{
	STDestroy(&obj->pushst);
	STDestroy(&obj->popst);
	free(obj);
}

3.4 设计循环队列

622. 设计循环队列 - 力扣(LeetCode)

 

typedef struct 
{
	int front;
	int rear;
	int k;//队列长度,假设为5
	int* a;//数组指针
} MyCircularQueue;

//这个函数动态开辟的obj或者数组都是为下面做铺垫的
MyCircularQueue* myCircularQueueCreate(int k) 
{
	MyCircularQueue* obj = (MyCircularQueue*)malloc(sizeof(MyCircularQueue));
	obj->a = (int*)malloc(sizeof(int) * (k + 1));
	obj->front = obj->rear = 0;
	obj->k = k;

	return obj;
}

bool myCircularQueueIsEmpty(MyCircularQueue* obj) 
{
	return obj->front == obj->rear;
}

bool myCircularQueueIsFull(MyCircularQueue* obj) 
{
	//(5+1)%(5+1)==0的时候是满的
	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 + 1) % (obj->k + 1);
	return true;
}

//从循环队列中删除一个元素,如果成功删除则返回真
bool myCircularQueueDeQueue(MyCircularQueue* obj) 
{
	if (myCircularQueueIsEmpty(obj))
		return false;

	obj->front = (obj->front + 1) % (obj->k + 1);
	return true;
}

int myCircularQueueFront(MyCircularQueue* obj) 
{
	if (myCircularQueueIsEmpty(obj))
		return -1;

	return obj->a[obj->front];
}

int myCircularQueueRear(MyCircularQueue* obj) 
{
	if (myCircularQueueIsEmpty(obj))
		return -1;

	return obj->a[((obj->rear - 1) + (obj->k + 1)) % (obj->k + 1)];
}

void myCircularQueueFree(MyCircularQueue* obj) 
{
	free(obj->a);
	free(obj);
}

3.5 选择题

现有一循环队列,其队头指针为front,队尾指针为rear;循环队列长度为N。其队内有效长度为?(假设队头不存放数据)

A (rear - front + N) % N + 1

B (rear - front + N) % N

C (rear - front) % (N + 1)

D (rear - front + N) % (N - 1)

答案是B,代入计算一下就可以

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值