数据结构:栈和队列的实现和图解二者相互实现

news2024/9/22 1:44:14

文章目录

  • 写在前面
    • 什么是栈
    • 栈的实现
  • 队列
    • 什么是队列
    • 队列的实现
  • 用队列实现栈
  • 用栈模拟队列

写在前面

栈和队列的实现依托的是顺序表和链表,如果对顺序表和链表不清楚是很难真正理解栈和队列的

下面为顺序表和链表的实现和图解讲解
手撕图解顺序表
手撕图解单链表

什么是栈

栈是一种数据结构,遵循的原则是后入先出,简单来说就是先入栈的最后出,最后入栈的先出

栈在实际应用中也是有很多场景,例如在使用网页时,我们点入了多个网页,退出返回的时候遵循的就是栈的后入先出原则

栈的实现

既然知道了栈的原则,那么就进行栈的实现用什么比较好,首先确定是可以用线性表实现,观察栈的使用原则不难发现,它只涉及一端的输入输出,这就意味着使用顺序表是很好的解决方案

栈的功能也不算多,入栈出栈检查栈满查看栈顶元素…整体看,栈就是顺序表的变形,这里对栈的实现不进行过多补充,重点在于后面和队列的相互实现

首先列出栈的定义和栈要实现的部分,声明和定义分离是个好习惯

// stack.h
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <stdbool.h>

// 支持动态增长的栈
typedef int STDataType;
typedef struct Stack
{
	STDataType* _a;
	int _top;		// 栈顶
	int _capacity;  // 容量 
}Stack;

// 初始化栈 
void StackInit(Stack* ps);

// 入栈 
void StackPush(Stack* ps, STDataType data);

// 出栈 
void StackPop(Stack* ps);

// 获取栈顶元素 
STDataType StackTop(Stack* ps);

// 获取栈中有效元素个数 
int StackSize(Stack* ps);

// 检测栈是否为空,如果为空返回非零结果,如果不为空返回0 
int StackEmpty(Stack* ps);

// 销毁栈 
void StackDestroy(Stack* ps);

下面是对栈的实现,几乎都是顺序表的基本操作,实现很简单

// stack.c
#include "stack.h"

void StackInit(Stack* ps)
{
	assert(ps);
	STDataType* tmp = NULL;
	int newcapacity = ps->_capacity == 0 ? 4 : ps->_capacity * 2;
	tmp = (STDataType*)realloc(ps->_a, sizeof(STDataType) * newcapacity);
	if (tmp == NULL)
	{
		perror("realloc fail");
		return;
	}
	ps->_capacity = newcapacity;
	ps->_a = tmp;
}

void StackPush(Stack* ps, STDataType data)
{
	assert(ps);
	if (ps->_capacity == ps->_top)
	{
		STDataType* tmp = NULL;
		int newcapacity = ps->_capacity == 0 ? 4:ps->_capacity * 2;
		tmp = (STDataType*)realloc(ps->_a,sizeof(STDataType)* newcapacity);
		if (tmp == NULL)
		{
			perror("realloc fail");
			return;
		}
		ps->_capacity = newcapacity;
		ps->_a = tmp;
	}
	ps->_a[ps->_top] = data;
	ps->_top++;
}

bool STEmpty(Stack* ps)
{
	assert(ps);
	
	return ps->_top == 0;
}

void StackPop(Stack* ps)
{
	assert(ps);
	assert(!STEmpty(ps));

	ps->_top--;
}

STDataType StackTop(Stack* ps)
{
	assert(ps);
	assert(!STEmpty(ps));
	
	return ps->_a[ps->_top-1];
}

int StackSize(Stack* ps)
{
	assert(ps);
	return ps->_top;
}

int StackEmpty(Stack* ps)
{
	assert(ps);
	if (0 == ps->_top)
		return 1;
	else
		return 0;
}

void StackDestroy(Stack* ps)
{
	assert(ps);
	ps->_capacity = 0;
	ps->_top = 0;
	free(ps->_a);
	ps->_a = NULL;
}

整体看,只要掌握了顺序表,栈的实现是很轻松的

队列

什么是队列

从名字来看,队列在日常生活中也经常遇到,不管在哪里都少不了排队的概念,而在有秩序的队列中,进队列都是从后面进队列,出队列都是从头出队列,这就类似于链表中的头删和尾插

那么队列的定义就有了,先进的先出,后进的后出,这就是队列的定义
队列实现还是和线性表有关,具体选顺序表还是链表要进行分析:

如果选用顺序表,顺序表的头删和尾插显然不如链表,你可能有这样的解决方案:我们可以选用数组下标当作头和尾,这样就能模拟头部少一个和尾部加一个,的确,这样可以解决,但是下一个问题是数组的长度并不好管控,如果想要完美的充分利用顺序表,就必须要使用循环数组,循环数组的下标并不好掌控,因此这里使用链表是很合适的选择

这里是关于循环数组的解析和模拟实现队列:
解析循环数组

队列的实现

// queue.h
#include<stdlib.h>
#include<assert.h>
#include<stdbool.h>

typedef int QDataType;
typedef struct QueueNode
{
	struct QueueNode* next;
	QDataType data;
}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);

上述函数的声明具体实现如下:

// queue.c
#include "queue.h"

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

	if (pq->ptail == NULL)
	{
		assert(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));

	// 1、一个节点
	// 2、多个节点
	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;
}

栈和队列本身是没有难度的,但是如果使用栈去实现队列,用队列去实现栈呢?
下面分析如何实现队列和栈的相互实现:

用队列实现栈

先看原理图:

在这里插入图片描述
代码实现也不算难,实现如下:

#include<stdlib.h>
#include<assert.h>
#include<stdbool.h>

typedef int QDataType;
typedef struct QueueNode
{
	struct QueueNode* next;
	QDataType data;
}QNode;
 
typedef struct Queue
{
	QNode* phead;
	QNode* ptail;
	int size;
}Queue;
#include "queue.h"

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

	if (pq->ptail == NULL)
	{
		assert(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));

	// 1、一个节点
	// 2、多个节点
	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;
}
typedef struct Mystack
{
	Queue push;
	Queue pop;
}Mystack;

void MsInit(Mystack* ps)
{
	assert(ps);
	QueueInit(&(ps->push));
	QueueInit(&(ps->pop));
}

void MsPush(Mystack* ps,QDataType x)
{
	assert(ps);
	QueuePush(&(ps->push), x);
}

void MsPop(Mystack* ps)
{
	while (QueueSize(&(ps->push)) > 1)
	{
		QueuePush(&(ps->pop), QueueFront(&(ps->push)));
		QueuePop(&(ps->push));
	}
	QueuePop(&(ps->push));
	while (!QueueEmpty(&(ps->pop)))
	{
		QueuePush(&(ps->push), QueueFront(&(ps->pop)));
		QueuePop(&(ps->pop));
	}
}

QDataType MsTop(Mystack* ps)
{
	assert(ps);
	return ps->push.ptail->data;
}

bool MsEmpty(Mystack* ps)
{
	if (ps->push.size == 0)
		return true;
	return false;
}

int main()
{
	Mystack s;
	MsInit(&s);
	MsPush(&s, 1);
	MsPush(&s, 2);
	MsPush(&s, 3);
	MsPush(&s, 4);
	MsPush(&s, 5);
	while (!MsEmpty(&s))
	{
		printf("%d ", MsTop(&s));
		MsPop(&s);
	}
	return 0;
}

用栈模拟队列

和上面的比起来,栈来实现队列就有一些改变:

在这里插入图片描述

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

// 支持动态增长的栈
typedef int STDataType;
typedef struct Stack
{
	STDataType* _a;
	int _top;		// 栈顶
	int _capacity;  // 容量 
}Stack;

void StackInit(Stack* ps)
{
	assert(ps);
	ps->_a = NULL;
	ps->_top = 0;
	ps->_capacity = 0;
}

void StackPush(Stack* ps, STDataType data)
{
	assert(ps);
	if (ps->_capacity == ps->_top)
	{
		STDataType* tmp = NULL;
		int newcapacity = ps->_capacity == 0 ? 4:ps->_capacity * 2;
		tmp = (STDataType*)realloc(ps->_a,sizeof(STDataType)* newcapacity);
		if (tmp == NULL)
		{
			perror("realloc fail");
			return;
		}
		ps->_capacity = newcapacity;
		ps->_a = tmp;
	}
	ps->_a[ps->_top] = data;
	ps->_top++;
}

bool STEmpty(Stack* ps)
{
	assert(ps);
	
	return ps->_top == 0;
}

void StackPop(Stack* ps)
{
	assert(ps);
	assert(!STEmpty(ps));

	ps->_top--;
}

STDataType StackTop(Stack* ps)
{
	assert(ps);
	assert(!STEmpty(ps));
	
	return ps->_a[ps->_top-1];
}

int StackSize(Stack* ps)
{
	assert(ps);
	return ps->_top;
}

int StackEmpty(Stack* ps)
{
	assert(ps);
	if (0 == ps->_top)
		return 1;
	else
		return 0;
}

void StackDestroy(Stack* ps)
{
	assert(ps);
	ps->_capacity = 0;
	ps->_top = 0;
	free(ps->_a);
	ps->_a = NULL;
}
typedef struct Myqueue
{
	Stack Push;
	Stack Pop;
}Myqueue;

void MqInit(Myqueue* pq)
{
	assert(pq);
	StackInit(&(pq->Push));
	StackInit(&(pq->Pop));
}

void MqPush(Myqueue* pq,STDataType x)
{
	assert(pq);
	StackPush(&(pq->Push), x);
}

void MqPop(Myqueue* pq)
{
	while (!StackEmpty(&(pq->Push)))
	{
		StackPush(&(pq->Pop), StackTop(&(pq->Push)));
		StackPop(&(pq->Push));
	}
	StackPop(&(pq->Pop));
	while (!StackEmpty(&(pq->Pop)))
	{
		StackPush(&(pq->Push), StackTop(&(pq->Pop)));
		StackPop(&(pq->Pop));
	}
}

STDataType MqTop(Myqueue* pq)
{
	// 把数据从push弄到pop
	while (!StackEmpty(&(pq->Push)))
	{
		StackPush(&(pq->Pop), StackTop(&(pq->Push)));
		StackPop(&(pq->Push));
	}
	STDataType ret = pq->Pop._a[pq->Pop._top-1];
	// 再把数据弄回去
	while (!StackEmpty(&(pq->Pop)))
	{
		StackPush(&(pq->Push), StackTop(&(pq->Pop)));
		StackPop(&(pq->Pop));
	}
	return ret;
}

int MqEmpty(Myqueue* pq)
{
	if (pq->Push._top == 0)
		return 1;
	return 0;
}

int main()
{
	Myqueue q;
	MqInit(&q);
	MqPush(&q, 1);
	MqPush(&q, 2);
	MqPush(&q, 3);
	MqPush(&q, 4);
	MqPush(&q, 5);
	while (!MqEmpty(&q))
	{
		printf("%d ", MqTop(&q));
		MqPop(&q);
	}
	return 0;
}

这样就可以直接实现了

整体来说,栈和队列的相互实现的意义不算很大,但是可以很好的更加深入的理解栈和队列的原理

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

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

相关文章

VMware虚拟机中配置静态IP

目录 环境原因基础概念VMnet网络IPV4网络私有地址范围Vmnet8的作用网路通信的过程解决方法1&#xff1a;修改k8s组件重新启动解决方法2&#xff1a;配置静态IP系统网卡设置设置虚拟机网关修改虚拟机网卡 环境 本机系统&#xff1a;windows11虚拟机系统&#xff1a;CentOS-7-x8…

【AutoGluon_03】保存模型并调用模型

在训练好autogluon模型之后&#xff0c;可以将模型进行保存。之后当有新的数据需要使用autogluon进行预测的时候&#xff0c;就可以直接加载原来训练好的模型进行训练。 import pandas as pd from sklearn.model_selection import train_test_split from autogluon.tabular im…

第九章:stack类

系列文章目录 文章目录 系列文章目录前言stack的介绍stack的使用成员函数使用stack 总结 前言 stack是容器适配器&#xff0c;底层封装了STL容器。 stack的介绍 stack的文档介绍 stack是一种容器适配器&#xff0c;专门用在具有后进先出操作的上下文环境中&#xff0c;其删除…

数字孪生技术从哪些方面为钢铁冶炼厂提高管理效率?

数字孪生系统是一种数字化技术&#xff0c;可以将物理世界中的实体对象、过程和数据进行数字化建模&#xff0c;以实现对其的可视化、模拟和优化。在炼铁生产管控中&#xff0c;数字孪生系统可以为以下方面提供支持&#xff1a; 炼铁生产线的可视化和控制&#xff1a;通过数字…

Web3 叙述交易所授权置换概念 编写transferFrom与approve函数

前文 Web3带着大家根据ERC-20文档编写自己的第一个代币solidity智能合约 中 我们通过ERC-20一种开发者设计的不成文规定 也将我们的代币开发的很像个样子了 我们打开 ERC-20文档 我们transfer后面的函数就是transferFrom 这个也是 一个账号 from 发送给另一个账号 to 数量 val…

指针初阶(1)

文章目录 目录1. 指针是什么2. 指针变量的类型2.1 指针变量-整数2.2 指针变量的解引用 3. 野指针3.1 野指针成因3.2 如何规避野指针 4. 指针运算4.1 指针-整数4.2 指针-指针4.3 指针的关系运算 附&#xff1a; 目录 指针是什么指针变量的类型野指针指针运算指针和数组二级指针…

redis集群设置

先下载redis数据库可以在一台机器上设置redis集群高可用 cd /etc/redis/ mkdir -p redis-cluster/redis600{1..6} for i in {1..6} do cp /opt/redis-5.0.7/redis.conf /etc/redis/redis-cluster/redis600$i cp /opt/redis-5.0.7/src/redis-cli /opt/redis-5.0.7/src/redis-s…

号外号外!首届开源 AI 游戏挑战赛圆满结束!

&#x1f917; 宝子们可以戳 阅读原文 查看文中所有的外部链接哟&#xff01; 北京时间 7 月 8 日到 7 月 10 日&#xff0c; 我们举办了首届开源 AI 游戏开发挑战赛。这是一场激动人心的赛事活动&#xff0c;游戏开发者在紧迫的 48 小时内使用 AI 创造、创新有创意的游戏。 本…

gazebo学习记录(杂乱)

一、完整系列教程 如何使用gazebo进行机器人仿真&#xff08;很重要&#xff09;&#xff1a;https://zhuanlan.zhihu.com/p/367796338 基础教程和关键概念讲解&#xff08;很重要&#xff09;&#xff1a;https://zhuanlan.zhihu.com/p/363385163 古月居&#xff1a;http://w…

Web自动化测试高级定位xpath

高级定位-xpath 目录 xpath 基本概念xpath 使用场景xpath 语法与实战 xpath基本概念 XPath 是一门在 XML 文档中查找信息的语言XPath 使用路径表达式在 XML 文档中进行导航XPath 的应用非常广泛XPath 可以应用在UI自动化测试 xpath 定位场景 web自动化测试app自动化测试 …

Selenium多浏览器处理

Python 版本 #导入依赖 import os from selenium import webdriverdef test_browser():#使用os模块的getenv方法来获取声明环境变量browserbrowser os.getenv("browser").lower()#判断browser的值if browser "headless":driver webdriver.PhantomJS()e…

每日一题——删除有序数组中的重复项

删除有序数组中的重复项 题目链接 注&#xff1a;本题所采用的方法是建立在移除元素的基础之上的&#xff0c;如果大家对双指针的方法不大了解&#xff0c;或者不会做《移除元素》这一题&#xff0c;建议先去看看&#x1f449;传送门 具体步骤 定义两个指针slow和fast&#…

计算并展示指定文件夹的大小

背景需求 有时候电脑里磁盘空间越来越小&#xff0c;不得不删除一些占空间大的文件。最笨的方法就是对某一个文件夹下一个一个查看大小&#xff0c;效率太慢。 效果图 Code import os import matplotlib.pyplot as plt plt.rcParams[font.family] sans-serif # 设置字体为…

Jenkins pipeline 脚本语言学习支持

1 引言 Groovy是用于Java虚拟机的一种敏捷的动态语言&#xff0c;它是一种成熟的面向对象编程语言&#xff0c;既可以用于面向对象编程&#xff0c;又可以用作纯粹的脚本语言。 使用该种语言不必编写过多的代码&#xff0c;同时又具有闭包和动态语言中的其他特性。 Groovy是一…

大模型开发(十四):使用OpenAI Chat模型 + Google API实现一个智能收发邮件的AI应用程序

全文共1.2w余字&#xff0c;预计阅读时间约24~40分钟 | 满满干货(附代码)&#xff0c;建议收藏&#xff01; 本文目标&#xff1a;将Gmail API接入Chat模型&#xff0c;编写一个智能收发邮件的AI应用程序 代码下载点这里 一、背景 大模型应用开发从谷歌云入手进行学习和AI…

Python爬虫的urlib的学习(学习于b站尚硅谷)

目录 一、页面结构的介绍  1.学习目标  2.为什么要了解页面&#xff08;html&#xff09;  3. html中的标签&#xff08;仅介绍了含表格、无序列表、有序列表、超链接&#xff09;  4.本节的演示 二、Urllib  1.什么是互联网爬虫&#xff1f;  2.爬虫核心  3.爬虫…

Sentinel 容灾中心的使用

Sentinel 容灾中心的使用 往期文章 Nacos环境搭建Nacos注册中心的使用Nacos配置中心的使用 熔断/限流结果 Jar 生产者 spring-cloud-alibaba&#xff1a;2021.0.4.0 spring-boot&#xff1a;2.6.8 spring-cloud-loadbalancer&#xff1a;3.1.3 sentinel&#xff1a;2021.0…

如何快速模拟一个后端 API

第一步&#xff1a;创建一个文件夹&#xff0c;用来存储你的数据 数据&#xff1a; {"todos": [{ "id": 1, "text": "学习html44", "done": false },{ "id": 2, "text": "学习css", "…

只会“点点点”,凭什么让开发看的起你?

众所周知&#xff0c;如今无论是大厂还是中小厂&#xff0c;自动化测试基本是标配了&#xff0c;毕竟像双 11、618 这种活动中庞大繁杂的系统&#xff0c;以及多端发布、多版本、机型发布等需求&#xff0c;但只会“写一些自动化脚本”很难胜任。这一点在招聘要求中就能看出来。…

Android 面试题 优化 (一)

&#x1f525; Android性能优化指标 &#x1f525; ​ &#x1f525; 包体积优化 &#x1f525; 安装包的大小会影响用户的安装率&#xff0c;如果一个包的太大&#xff0c;用户安装的意愿会大大降低。 经过包分析可以看到&#xff0c;安装包最大的部分是资源和第三方库&#…