数据结构-栈和队列力扣题

目录

有效的括号

用队列实现栈

 用栈实现队列

 设计循环队列


有效的括号

题目链接:力扣(LeetCode)

思路: 这道题可以用栈来解决,先让字符串中的左括号' ( ',' [ ',' { '入栈,s指向字符串下一个字符,如果该字符也是左括号,那就继续入栈,如果是右括号,那就让其与栈顶元素相匹配(每次都要弹出栈顶元素),匹配上了,继续循环,匹配不上就返回false,注意在每次返回false之前都要销毁栈。

还要考虑极端情况,如果全是左括号,我们要在代码最后进行判空,不为空,返回false,同时,这次判空也能解决前面几对都匹配上,只有最后一个左括号没匹配上的问题(例如:"()[]{}{")。

如果全是右括号,说明整个过程中没有入栈元素,此时判空,如果为空返回false,同时,这次判空也能解决前面几对都匹配上,只有最后一个右括号没匹配上的问题(例如:"()[]{}}")。

如果用C语言来解题的话,栈需要自己写。

代码如下:

typedef int STDatatype;
typedef struct Stack
{STDatatype* a;int top;int capacity;
}ST;//初始化栈
void STInit(ST* pst)
{assert(pst);pst->a = NULL;pst->top = 0;pst->capacity = 0;
}//入栈
void STPush(ST* pst, STDatatype x)
{//开辟空间if (pst->top == pst->capacity){int newcapacity = pst->capacity == 0 ? 4 : pst->capacity * 2;STDatatype* tmp = (STDatatype*)realloc(pst->a, sizeof(STDatatype) * newcapacity);if (tmp == NULL){perror("realloc fail");return;}pst->a = tmp;pst->capacity = newcapacity;}//插入pst->a[pst->top] = x;pst->top++;
}
//判空函数
bool STEmpty(ST* pst)
{assert(pst);return pst->top == 0;
}
//出栈
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];
}
//获取栈中有效数据的个数
int STSize(ST* pst)
{assert(pst);return pst->top;
}
//销毁栈
void STDestory(ST* pst)
{assert(pst);free(pst->a);pst->a = NULL;pst->top = pst->capacity = 0;
}bool isValid(char* s) {ST st;STInit(&st);while(*s){if(*s=='('||*s=='['||*s=='{'){STPush(&st,*s);}else{if(STEmpty(&st)){STDestory(&st);return false;}char top=STTop(&st);STPop(&st);if((top!='('&&*s==')')||(top!='['&&*s==']')||(top!='{'&&*s=='}')){STDestory(&st);return false;}}++s;}bool ret=STEmpty(&st);STDestory(&st);return ret;
}

用队列实现栈

题目链接:力扣(LeetCode)

 思路:队列是先入先出,栈是先入后出,要用队列实现栈,我们可以定义两个栈q1和q2,当它们都为空时,随便选一个存入数据,假设q1中有数据1 2 3 4,我们可以把q1中的1 2 3 push进q2中,然后把q1中的4 pop出去,接着把q2中的1 2 push进q1,然后把q2中的3 pop出去,这样循环在q1和q2中倒数据,就实现了4 3 2 1依次出栈,即先入后出。

当我们在出栈的同时,想要入栈,就把数据push进有数据的队列即可。

想要用C语言做这道题,队列的实现代码也要自己写。

注意,我们下列代码是结构体的三层嵌套,所以销毁时要先销毁q1和q2,再销毁obj,如果只销毁obj,由于我们的队列q1和q2中分别有两个头尾指针还有节点,会造成内存泄漏的问题。

它们的关系图如下:

代码如下:

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)
{pq->phead = NULL;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->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++;
}//判空函数
bool QueueEmpty(Queue* pq)
{assert(pq);return pq->size ==0 ;
}//队头出队列
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;
}//销毁队列
void DestoryQueue(Queue* pq)
{assert(pq);while (pq->phead){QNode* next = pq->phead->next;free(pq->phead);pq->phead = next;}pq->phead = pq->ptail = NULL;pq->size = 0;
}typedef struct {Queue q1;Queue q2;
} MyStack;MyStack* myStackCreate() {MyStack* obj=(MyStack*)malloc(sizeof(MyStack));if(obj==NULL){perror("malloc fail");return NULL;}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* pemptyq=&obj->q1;Queue* pnoemptyq=&obj->q2;if(!QueueEmpty(&obj->q1)){pemptyq=&obj->q2;pnoemptyq=&obj->q1;}while(Queuesize(pnoemptyq)>1){QueuePush(pemptyq,QueueFront(pnoemptyq));QueuePop(pnoemptyq);}int top=QueueFront(pnoemptyq);QueuePop(pnoemptyq);return top;}int myStackTop(MyStack* obj) {if(!QueueEmpty(&obj->q1))return QueueBack(&obj->q1);elsereturn QueueBack(&obj->q2);}bool myStackEmpty(MyStack* obj) {assert(obj);return QueueEmpty(&obj->q1)&&QueueEmpty(&obj->q2);}void myStackFree(MyStack* obj) {DestoryQueue(&obj->q1);DestoryQueue(&obj->q2);free(obj);
}

 用栈实现队列

题目链接:力扣(LeetCode)

思路:这道题用上道题的思路也能实现,但是过于复杂。

简单思路:我们定义两个栈pushstpopst,栈中数据遵循先入后出的原则,如果在pushstpush进去1 2 3 4,那他从栈顶到栈底依次是 4 3 2 1 ,但是如果我们把pushst中的数据再pushpopst中,那popst中从栈顶到栈底依次是 1 2 3 4,此时我们只要将popst中的数据按照栈本身先入后出的原则pop出去,就是1 2 3 4,这样就实现了先入先出。如下图:

当我们在出队列的同时,想要入队列,要先等popst中的数据出完才行,所以当popst为空,pushst不为空时,才能把pushst中的数据往popstpush

代码如下:

typedef int STDatatype;
typedef struct Stack
{STDatatype* a;int top;int capacity;
}ST;//初始化栈
void STInit(ST* pst)
{assert(pst);pst->a = NULL;pst->top = 0;pst->capacity = 0;
}//入栈
void STPush(ST* pst, STDatatype x)
{//开辟空间if (pst->top == pst->capacity){int newcapacity = pst->capacity == 0 ? 4 : pst->capacity * 2;STDatatype* tmp = (STDatatype*)realloc(pst->a, sizeof(STDatatype) * newcapacity);if (tmp == NULL){perror("realloc fail");return;}pst->a = tmp;pst->capacity = newcapacity;}//插入pst->a[pst->top] = x;pst->top++;
}
//判空函数
bool STEmpty(ST* pst)
{assert(pst);return pst->top == 0;
}
//出栈
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];
}
//获取栈中有效数据的个数
int STSize(ST* pst)
{assert(pst);return pst->top;
}
//销毁栈
void STDestory(ST* pst)
{assert(pst);free(pst->a);pst->a = NULL;pst->top = pst->capacity = 0;
}
typedef struct {ST pushst;ST popst;
} MyQueue;MyQueue* myQueueCreate() {MyQueue*obj=(MyQueue*)malloc(sizeof(MyQueue));if(obj==NULL){perror("malloc fail\n");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) {assert(obj);return STEmpty(&obj->pushst)&&STEmpty(&obj->popst);
}void myQueueFree(MyQueue* obj) {STDestory(&obj->pushst);STDestory(&obj->popst);free(obj);
}

 设计循环队列

题目链接:力扣(LeetCode)

思路: 本题用数组队列和链表队列都能实现,在这里我们使用数组队列,首先,要设计一个循环队列,我们就要知道队列什么时候满,什么时候空,空很容易判断,当front=rear时就为空,问题是当我们循环一圈以后,队列已经满了,但此时front也等于rear,所以为了不发生混淆,我们在开辟空间时多开辟一块,假设要存7个数据就开辟8个空间:

此时当rear+1==front时就为满。但这只是上图为了形象展示,实际上在数组中,每存一个数,rear++,但是数组首尾并没有相连,不能用rear+1==front判断是否满了,我们可以用下标rear,当(rear+1)%(k+1)==front时就说明队列满了

而要在队列中插入数据,每次插入之后下标rear++,但是当队列满了之后,rear就是数组中最后一个下标,这时如果我们在队头出了两个数据,想再往队列里插数据,就要让rear回到开始的位置,所以每次rear++后,让rear=rear%(k+1),此时再插入,就形成了一个完美的循环,同理,删除数据也一样,每次删完都让front=front%(k+1)

obj->a[(obj->rear+obj->k)%(obj->k+1)]这段代码是为了返回队尾元素。

代码如下:

typedef struct {int front;int rear;int k;int*a;
} MyCircularQueue;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) {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->rear)%(obj->k+1);return true;
}bool myCircularQueueDeQueue(MyCircularQueue* obj) {if(myCircularQueueIsEmpty(obj))return false;obj->front++;obj->front=(obj->front)%(obj->k+1);return true;
}int myCircularQueueFront(MyCircularQueue* obj) {if(myCircularQueueIsEmpty(obj))return -1;elsereturn obj->a[obj->front];
}int myCircularQueueRear(MyCircularQueue* obj) {if(myCircularQueueIsEmpty(obj))return -1;elsereturn obj->a[(obj->rear+obj->k)%(obj->k+1)];
}void myCircularQueueFree(MyCircularQueue* obj) {free(obj->a);free(obj);
}

栈与队列的内容到这里就结束了,下节开始学习堆与二叉树

未完待续。。。 

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

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

潼南柠檬产业发展大会举行 这三个场景“柠”聚了人气

华龙网讯(首席记者 羊华)今(6)日下午,2023中国潼南柠檬产业发展大会正式举行。潼南区准备了“大礼包”,既有专业论坛峰会,也首发了“柠檬产业大脑”,还进行了招商引资集中签约&#…

nacos做服务配置和服务器发现

一、创建项目 1、创建一个spring-boot的项目 2、创建三个模块file、system、gateway模块 3、file和system分别配置启动信息,并且创建一个简单的控制器 server.port9000 spring.application.namefile server.servlet.context-path/file4、在根目录下引入依赖 <properties&g…

让深度神经网络绘画以了解它们是如何工作的

一、说明 深度学习如此有效&#xff0c;这真是一个谜。尽管有一些关于深度神经网络为何如此有效的线索&#xff0c;但事实是没有人完全确定&#xff0c;并且深度学习的理论理解是一个非常活跃的研究领域。 在本教程中&#xff0c;我们将以一种不寻常的方式触及问题的一个小方面…

计算机基础知识49

三板斧的使用(views.py) 三个方法&#xff1a;HttpResponse: 返回的是字符串render : 返回html文件redirect : 返回加载HTML页面的 def html(request):print(from html)# return HttpResponse(request) # 它返回的是字符串return render(request,html.html) # 返回html# ret…

【c++】——类和对象(中)——赋值运算符重载

作者:chlorine 专栏:c专栏 你站在原地不动,就永远都是观众。 【学习目标】 拷贝复制——赋值运算符重载 目录 &#x1f393;运算符重载的初步认识 &#x1f308;运算符重载 &#x1f308;赋值运算符重载格式 (上) &#x1f308;operator__判断俩个日期是否相等 &#x…

Mysql 一步到位实现插入或替换数据(REPLACE INTO语句)

单条数据插入/替换 比如有一个数据表叫test_table&#xff0c;包含: 主键&#xff1a;key_id数据&#xff1a;value 运行&#xff1a; REPLACE INTO test_table (key_id,value) VALUES ("id_1","value_1"); REPLACE INTO test_table (key_id,value) VAL…

使用 Socks5 来劫持 HTTPS(TCP-TLS) 之旅

MITM 劫持的过程中&#xff0c;HTTP 协议并不是唯一选择。 实际在 MITM 使用过程中&#xff0c;BurpSuite 和 Yakit 提供的交互式劫持工具只能劫持 HTTP 代理的 TLS 流量&#xff1b;但是这样是不够的&#xff0c;有时候我们并不能确保 HTTP 代理一定生效&#xff0c;或者说特…

Adobe Photoshop 2020给证件照换底

1.导入图片 2.用魔法棒点击图片 3.点选择&#xff0c;反选 4.选择&#xff0c;选择并遮住 5.用画笔修饰证件照边缘 6. 7.更换要换的底的颜色 8.新建图层 9.使用快捷键altdelete键填充颜色。 10.移动图层&#xff0c;完成换底。

工业摄像机参数计算

在工业相机选型的时候有点懵&#xff0c;有一些参数都不知道咋计算的。有些概念也没有区分清楚。‘’ 靶面尺寸 CMOS 或者是 CCD 使用几分之几英寸来标注的时候&#xff0c;这个几分之几英寸计算的是什么尺寸&#xff1f; 一开始我以为这个计算的就是靶面的实际对角线的尺寸…

clickhouse安装与远程访问

安装&#xff08;本文以ubuntu系统为例&#xff09; 单节点设置​ 为了延迟演示分布式环境的复杂性&#xff0c;我们将首先在单个服务器或虚拟机上部署ClickHouse。ClickHouse通常是从deb或rpm包安装&#xff0c;但对于不支持它们的操作系统也有其他方法。 例如&#xff0c;…

贺天下功夫酱酒闪耀亮相2023佛山秋色系列活动

11月1日至5日&#xff0c;2023年广东非遗周暨佛山秋色巡游系列活动在佛山举行&#xff0c;以“品味佛山 秋醉岭南”为主题&#xff0c;好戏连台。贵州贺天下酒业独家赞助佛山祖庙秋祭、乡饮酒礼&#xff0c;还全面参与佛山秋色巡游、佛山非遗美食展、佛山非遗音乐会等多个活动&…

Tomcat隐藏版本号和关闭默认管理页面

一. 隐藏Tomcat异常页面中的版本信息&#xff0c;Tomcat服务器版本号泄露 Tomcat/8.5.xx相关版本号等信息&#xff0c;是不安全的。这会被黑客获取到&#xff0c;利用该版本的其他漏洞对服务器进行异常操作&#xff0c;所以需要隐藏掉。 进入tomcat安装目录 apache-tomcat-8.…