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

news2024/9/28 13:22:31

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,代入计算一下就可以

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2173623.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

爬取元气手机壁纸简单案例(仅用于教学,禁止任何非法获利)

爬虫常用的库 爬虫&#xff08;Web Scraping&#xff09;是一种从网页上提取数据的技术。在 Python 中&#xff0c;有许多库可以帮助实现这一目标。以下是一些常用的爬虫库&#xff0c;以及对 BeautifulSoup 的详细介绍。 常用爬虫库 1.Requests ​ a.功能&#xff1a;用于发…

利用 Llama-3.1-Nemotron-51B 推进精度-效率前沿的发展

今天&#xff0c;英伟达™&#xff08;NVIDIA&#xff09;发布了一款独特的语言模型&#xff0c;该模型具有无与伦比的准确性和效率性能。Llama 3.1-Nemotron-51B 源自 Meta 的 Llama-3.1-70B&#xff0c;它采用了一种新颖的神经架构搜索&#xff08;NAS&#xff09;方法&#…

MySQL的安装(环境为CentOS云服务器)

卸载内置环境 我们初期使用root账号&#xff0c;后期再切换成普通账号 使用 ps axj | grep mysql 查看系统中是否有MySQL相关的进程 使用 systemctl stop mysqld 关停进程 使用 rpm -qa | grep mysql 查看MySQL相关的安装包 使用 rpm -qa | grep mysql | xargs yum -y remo…

试用Debian12.7和Ubuntu24.4小札

Debian GNU/Linux 12 (bookworm)和Ubuntu 24.04.1 LTS是现阶段&#xff08;2024年9月26日&#xff09;两个发行版的最新版本。Ubuntu Server版本默认就不带桌面&#xff08;ubuntu-24.04-live-server-amd64.iso&#xff09;&#xff0c;这个默认就是最小化安装&#xff08;安装…

长芯微LPQ76930锂电池组保护芯片完全P2P替代BQ76930

LPQ76930系列芯片可作为 3-15 节串联电池组监控和保护解决方案的一部分。通过 TWI 通信&#xff0c;MCU 可以使用 LPQ76930 来执行电池管理功能1&#xff0c;例如监测&#xff08;电池电压、电池 组电流、电池组温度&#xff09;、保护&#xff08;控制充电/放电 FET&#xff0…

java中的强软弱虚

在java中对象的引用有强、软、弱、虚四种&#xff0c;这些引用级别的区别主要体现在对象的生命周期、回收时机的不同。 文章目录 准备工作1. 设置内存2. 内存检测 强引用软引用弱引用虚引用 准备工作 1. 设置内存 为方便调试&#xff0c;将内存设置为16MB 依次点击菜单栏的R…

springboot基于学习行为的学生选课成绩分析系统设计与实现

目录 功能介绍使用说明系统实现截图开发核心技术介绍&#xff1a;开发步骤编译运行核心代码部分展示开发环境需求分析详细视频演示源码获取 功能介绍 学生 课程学习行为数据录入: 学生填写每门课程的学习时长、学习态度、课后作业质量等。 课程学习行为数据修改: 学生可修改已…

基于SpringBoot+Vue的大学生公考服务平台

作者&#xff1a;计算机学姐 开发技术&#xff1a;SpringBoot、SSM、Vue、MySQL、JSP、ElementUI、Python、小程序等&#xff0c;“文末源码”。 专栏推荐&#xff1a;前后端分离项目源码、SpringBoot项目源码、Vue项目源码、SSM项目源码 精品专栏&#xff1a;Java精选实战项目…

php 平滑重启 kill -SIGUSR2 <PID> pgrep命令查看进程号

有时候我们使用nginx 大家都知道平滑重启命令: /web/nginx/sbin/nginx -s reload 但大家对php-fpm 重启 可能就是简单暴力的kill 直接搞起了 下面介绍一个sh 文件名保存为start_php.sh 来对php-fpm 进行平滑重启 #!/bin/bash# 检查 PHP-FPM 是否运行 if ! pgrep php-…

JAVA开源项目 技术交流分享平台 计算机毕业设计

本文项目编号 T 053 &#xff0c;文末自助获取源码 \color{red}{T053&#xff0c;文末自助获取源码} T053&#xff0c;文末自助获取源码 目录 一、系统介绍二、演示录屏三、启动教程四、功能截图五、文案资料5.1 选题背景5.2 国内外研究现状5.3 可行性分析 六、核心代码6.1 新…

论文阅读(十一):CBAM: Convolutional Block Attention Module

文章目录 1.Introduction2.Convolutional Block Attention ModuleExperimentsConclusion 论文题目&#xff1a;CBAM: Convolutional Block Attention Module&#xff08;CBAM&#xff1a;卷积注意力机制&#xff09;   论文链接&#xff1a;点击跳转   代码链接&#xff1a…

运维,36岁,正在经历中年危机,零基础入门到精通,收藏这一篇就够了

我今年36岁&#xff0c;运维经理&#xff0c;985硕士毕业&#xff0c;目前正在经历中年危机&#xff0c;真的很焦虑&#xff0c;对未来充满担忧。不知道这样的日子还会持续多久&#xff0c;突然很想把这些年的经历记录下来&#xff0c;那就从今天开始吧。 先说一下我的中年危机…

中国科学技术大学《2020年+2021年845自动控制原理真题》 (完整版)

本文内容&#xff0c;全部选自自动化考研联盟的&#xff1a;《25届中国科学技术大学845自控考研资料》的真题篇。后续会持续更新更多学校&#xff0c;更多年份的真题&#xff0c;记得关注哦~ 目录 2020年真题 2021年真题 Part1&#xff1a;2020年2021年完整版真题 2020年真…

python实战三:使用循环while模拟用户登录

# (1)初始变量 i0 while i<3: # (2)条件判断# (3)语句块user_name input(请输入您的用户名&#xff1a;)pwd input(请输入您的密码&#xff1a;)#登陆判断 if elseif user_namewwl and pwd66666666:print(系统正在登录&#xff0c;请稍后)#需要改变循环变量&#xff0c;目…

一文读懂:监督式微调(SFT)

监督式微调 (Supervised fine-tuning)&#xff0c;也就是SFT&#xff0c;就是拿一个已经学了不少东西的大型语言模型&#xff0c;然后用一些特定的、已经标记好的数据来教它怎么更好地完成某个特定的任务。就好比你已经学会了做饭&#xff0c;但是要特别学会怎么做川菜&#xf…

以流量裂变为目标,驱动动销新潮流

在当今数字化商业世界&#xff0c;流量成为关键。而以流量裂变为目标的动销策略&#xff0c;正成为企业致胜法宝。 流量裂变&#xff0c;即让流量呈指数级增长。它依靠用户传播分享&#xff0c;能快速扩大品牌曝光度与影响力&#xff0c;提高获客效率。动销则是推动产品销售&am…

【幂简集成】手机归属地查询API,精准获取号码所在地,提升数据准确率

在互联网与移动通信技术迅猛进步的背景下&#xff0c;手机号码已成为企业经营及个人生活中的重要工具。对众多企业而言&#xff0c;通过手机号归属地查询&#xff0c;既可优化营销策略&#xff0c;又能提高客户服务精确性。手机号归属地查询 API 的问世&#xff0c;旨在满足这一…

AI产品经理学习路径:从零基础到精通,从此篇开始!

一、AI产品经理和和通用型产品经理的异同&#xff1a; 市面上不同的公司对产品经理的定位有很大的差别&#xff0c;一名合格的产品经理是能对软件产品整个生命周期负责的人。 思考框架相同&#xff1a; AI产品经理和通用型软件产品经理的底层思考框架是一样的&#xff0c;都是…

旺店通ERP集成金蝶K3(旺店通主供应链)

源系统成集云目标系统 金蝶K3介绍 金蝶K3是一款ERP软件&#xff0c;它集成了供应链管理、财务管理、人力资源管理、客户关系管理、办公自动化、商业分析、移动商务、集成接口及行业插件等业务管理组件。以成本管理为目标&#xff0c;计划与流程控制为主线&#xff0c;通过对成…

protobuff中的required有什么用?

大家在proto2 应该经常看到如下msg表达: message MsgType3 { required int32 value1 1; required int32 value2 2; } 在protobuff中的required 有什么作用&#xff1f;在 Protocol Buffers&#xff08;protobuf&#xff09;中&#xff0c;required 关键字用于指定某个字段是…