当前位置:网站首页>Realize queue with stack and stack with queue (C language \leetcode\u 232+225)
Realize queue with stack and stack with queue (C language \leetcode\u 232+225)
2022-07-01 13:53:00 【Brant_ zero】
Stack and queue were implemented two days ago , Now do two classic examples to consolidate your knowledge .
Topic link :
232. Using stack to realize queue - Power button (LeetCode)
225. Using queue to implement stack - Power button (LeetCode)
Catalog
One 、 Using stack to realize queue
Two 、 Using queue to implement stack
3.1 Stack --> queue Source code
3.2 queue --> Stack Source code
One 、 Using stack to realize queue
Ideas :
① Build two stacks to realize the queue . A stack is input Stack , Only save data ; A stack is output Stack , Only responsible for data .
② When data comes out , First judge output Is the stack empty (StackEmpty(&output)), If it is empty , To put input Data in the stack Import all into output In the stack , And then there's output Top element of stack , Delete one more output Data in the stack .
At this time, let's analyze why output Data is inverted only when it is empty .
Pay attention ! The stack is First in, then out Oh ! Only when output Data can only be inverted when it is empty , If not, then the inserted data will disrupt the order of the stack .
Because we're using C Language to do this problem , We need to create our own stack , This is more troublesome , Fortunately, we implemented a stack two days ago , It can be used directly .
The source code is long , I put it at the end , You can jump through the directory .
Two 、 Using queue to implement stack
Ideas :
① A queue holds the input data , A queue is exclusively empty , It is used to save data when exporting data . The two queues will switch functions every time they send data .
② When exporting data , To import the data in the queue storing data into the empty queue , Until only one data is left . Then output this data , If it is Pop type , After output, delete the data , If it is Top type , Then the data is output and inserted into the inverted data queue .
step :
One 、 insert data
If q1 It's empty , be q1 It is a queue for reversing data , So put q2, vice versa ,q2 Insert for empty data q1.
Two 、 Take the data
1. Import all the remaining data except the last data into the inverted data queue , Then output the last data left .
2. If the requirement is Pop type , After output, delete the data ; If it is Top type , Then the data is output and inserted into the inverted data queue .
3、 ... and 、 Source code
because C Languages do not have libraries of these structures , We can only rub out the stack and queue by hand , Fortunately, we implemented stack and queue two days ago , At this time, we can copy it directly and apply it , So there is a little more code .
3.1 Stack --> queue Source code
#include <stdio.h>
#include <assert.h>
#include <stdbool.h>
#include <stdlib.h>
typedef int STDateType;
typedef struct Stack
{
STDateType* a;
int top; // Identify the data at the top of the stack
int capacity; // Dynamic Capacity expansion
}ST;
void StackInit(ST* ps);
void StackDestory(ST* ps);
void StackPush(ST* ps, STDateType x);
void StackPop(ST* ps);
STDateType StackTop(ST* ps); // Take the element at the top of the stack
bool StackEmpty(ST* ps); // Judge whether the stack is empty
int StackSize(ST* ps); // Know the stack size
void StackInit(ST* ps)
{
assert(ps);
ps->a = NULL;
ps->top = 0;
ps->capacity = 0;
}
void StackDestory(ST* ps)
{
assert(ps);
free(ps->a);
ps->a = NULL;
ps->top = ps->capacity = 0;
}
void StackPush(ST* ps, STDateType x)
{
assert(ps);
if (ps->capacity == ps->top)
{
int NewCapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
STDateType* temp = (STDateType * )realloc(ps->a, sizeof(STDateType) * NewCapacity);
if (temp == NULL)
{
printf("realloc fail");
exit(-1);
}
ps->a = temp;
ps->capacity = NewCapacity;
}
ps->a[ps->top] = x;
ps->top++;
}
void StackPop(ST* ps)
{
assert(ps);
assert(!StackEmpty(ps));
ps->top--;
}
STDateType StackTop(ST* ps)
{
assert(ps);
assert(!StackEmpty(ps));
return ps->a[ps->top - 1];
}
bool StackEmpty(ST* ps)
{
assert(ps);
return ps->top == 0;
}
int StackSize(ST* ps)
{
assert(ps);
return ps->top;
}
typedef struct {
ST input; //input Stack
ST output; //output Stack
} MyQueue;
// Create the queue And back to
MyQueue* myQueueCreate() {
// Open up a space for structural variables
// Represents the structure we created ourselves MyQueue
MyQueue* obj =(MyQueue*)malloc(sizeof(MyQueue));
// Be careful , Creating a MyQueue in , We created a stack , If we call a function of the stack , It is necessary to pass the address of the stack into the function to conform to its type
StackInit(&obj->input);
StackInit(&obj->output);
return obj;
}
void myQueuePush(MyQueue* obj, int x) {
// Put data into input Stack
StackPush(&obj->input,x);
}
int myQueuePop(MyQueue* obj) {
// Pop up the data
// If output empty , It indicates that the data stack is empty , Import data
if(StackEmpty(&obj->output))
{
// until input It's empty
while(!StackEmpty(&obj->input))
{
// take input Data into output
// Insert a Pop One
StackPush(&obj->output,StackTop(&obj->input));
StackPop(&obj->input);
}
}
int ret=StackTop(&obj->output);
StackPop(&obj->output);
return ret;
}
bool myQueueEmpty(MyQueue* obj) {
// Two stacks are empty , That is, the queue is empty
return (StackEmpty(&obj->input)&& StackEmpty(&obj->output));
}
int myQueuePeek(MyQueue* obj) {
// If the queue is empty
if (myQueueEmpty(obj))
{
return -1;
}
if(StackEmpty(&obj->output))
{
while(!StackEmpty(&obj->input))
{
// take input Data into output
StackPush(&obj->output,StackTop(&obj->input));
StackPop(&obj->input);
}
}
return StackTop(&obj->output);
}
void myQueueFree(MyQueue* obj) {
StackDestory(&obj->input);
StackDestory(&obj->output);
free(obj);
}
3.2 queue --> Stack Source code
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <assert.h>
typedef int QDataType;
typedef struct QueueNode
{
struct QueueNode* next;
QDataType data;
}QNode;
typedef struct Queue
{
QNode* head;
QNode* tail;
}Queue;
void QueueInit(Queue* pq)
{
assert(pq);
pq->head = pq->tail = NULL;
}
void QueueDestroy(Queue* pq)
{
assert(pq);
QNode* Dest = pq->head;
while (Dest)
{
QNode* temp = Dest->next;
free(Dest);
Dest = temp;
}
pq->head = pq->tail = NULL;
}
void QueuePush(Queue* pq, QDataType x)
{
assert(pq);
// Create a node
QNode* newnode = (QNode*)malloc(sizeof(QNode));
if (newnode == NULL)
{
printf("malloc fail\n");
exit(-1);
}
newnode->data = x;
newnode->next = NULL;
// Judge pq Is it an empty node
// If it is Will newnode Set as the first node of the current queue
// If not Will newnode link to pq Next position of
if (pq->tail == NULL)
{ // Both nodes point to newnode Indicates that there is only one element in the queue
pq->head = pq->tail = newnode;
}
else
{
//1. take newnode link to tail Behind
pq->tail->next = newnode;
//2. take newnode Replace with new tail
pq->tail = newnode;
}
}
bool QueueEmpty(Queue* pq)
{
assert(pq);
return pq->head == NULL;
}
void QueuePop(Queue* pq)
{
assert(pq);
assert(!QueueEmpty(pq));
// Make an extra judgment , Solve if there is only one node left ,pop Words lead to tail For the wild pointer
if (pq->head->next == NULL)
{
free(pq->head);
pq->head = pq->tail = NULL;
}
else
{
QNode* next = pq->head->next;
free(pq->head);
pq->head = next;
}
}
QDataType QueueFront(Queue* pq)
{
assert(pq);
assert(!QueueEmpty(pq));
return pq->head->data;
}
QDataType QueueBck(Queue* pq)
{
assert(pq);
assert(!QueueEmpty(pq));
return pq->tail ->data;
}
int QueueSize(Queue *pq)
{
assert(pq);
int count = 0;
QNode* cur = pq->head;
while (cur)
{
cur = cur->next;
count++;
}
return count;
}
typedef struct {
Queue q1; // queue 1
Queue q2; // queue 2
} MyStack;
MyStack* myStackCreate() {
MyStack* obj = (MyStack*)malloc(sizeof(MyStack));
if (obj == NULL)
{
return 0;
}
// Initialize these two queues
QueueInit(&obj->q1);
QueueInit(&obj->q2);
return obj;
}
bool myStackEmpty(MyStack* obj) {
return QueueEmpty(&obj->q1) && QueueEmpty(&obj->q2);
}
void myStackPush(MyStack* obj, int x) {
// If q1 It's empty , Then go q2 Put data in
if (QueueEmpty(&obj->q1))
{
QueuePush(&obj->q2, x);
}
else
{
QueuePush(&obj->q1, x);
}
}
int myStackPop(MyStack* obj) {
// If q1 It's empty , It's from q2 Go to q1 Inside guide data
if (QueueEmpty(&obj->q1))
{
while (!((&obj->q2)->head->next == NULL))
{
QueuePush(&obj->q1, QueueFront(&obj->q2));
QueuePop(&obj->q2);
}
int ret = QueueFront(&obj->q2);
QueuePop(&obj->q2);
return ret;
}
else
{
while (!((&obj->q1)->head->next == NULL))
{
QueuePush(&obj->q2, QueueFront(&obj->q1));
QueuePop(&obj->q1);
}
int ret = QueueFront(&obj->q1);
QueuePop(&obj->q1);
return ret;
}
}
int myStackTop(MyStack* obj) {
// If q1 It's empty , Is the location where the data except the top of the stack is stored
if (QueueEmpty(&obj->q1))
{
while (!((&obj->q2)->head->next == NULL))
{
QueuePush(&obj->q1, QueueFront(&obj->q2));
QueuePop(&obj->q2);
}
int ret = QueueFront(&obj->q2);
QueuePush(&obj->q1,ret);
QueuePop(&obj->q2);
return ret;
}
else
{
while (!((&obj->q1)->head->next == NULL))
{
QueuePush(&obj->q2, QueueFront(&obj->q1));
QueuePop(&obj->q1);
}
int ret = QueueFront(&obj->q1);
QueuePush(&obj->q2,ret);
QueuePop(&obj->q1);
return ret;
}
}
void myStackFree(MyStack* obj) {
QueueDestroy(&obj->q1);
QueueDestroy(&obj->q2);
free(obj);
}
边栏推荐
- SWT/ANR问题--如何捕获性能的trace
- QT learning management system
- 龙蜥社区开源 coolbpf,BPF 程序开发效率提升百倍
- Anti fraud, refusing to gamble, safe payment | there are many online investment scams, so it's impossible to make money like this
- 关于佛萨奇2.0“Meta Force原力元宇宙系统开发逻辑方案(详情)
- Computer network interview knowledge points
- Applet - multiple text line breaks in view
- 6年技术迭代,阿里全球化出海&合规的挑战和探索
- QT社团管理系统
- 基于算力驱动、数据与功能协同的分布式动态(协同)渲染/功能运行时
猜你喜欢
Fiori applications are shared through the enhancement of adaptation project
QT社团管理系统
Build a vc2010 development environment and create a tutorial of "realizing Tetris game in C language"
当你真的学会DataBinding后,你会发现“这玩意真香”!
MySQL六十六问,两万字+五十图详解!复习必备
开源者的自我修养|为 ShardingSphere 贡献了千万行代码的程序员,后来当了 CEO
IO的几种模型 阻塞,非阻塞,io多路复用,信号驱动和异步io
Summary of interview questions (1) HTTPS man in the middle attack, the principle of concurrenthashmap, serialVersionUID constant, redis single thread,
【IoT毕设.下】STM32+机智云AIoT+实验室安全监控系统
French Data Protection Agency: using Google Analytics or violating gdpr
随机推荐
面试题目总结(1) https中间人攻击,ConcurrentHashMap的原理 ,serialVersionUID常量,redis单线程,
Leetcode question 1: sum of two numbers (3 languages)
This paper introduces an implementation scheme to enhance the favorite transaction code management tool in SAP GUI
Yan Rong looks at how to formulate a multi cloud strategy in the era of hybrid cloud
清华章毓晋老师新书:2D视觉系统和图像技术(文末送5本)
2. Sensor size "recommended collection"
[安网杯 2021] REV WP
Go整合Logrus实现日志打印
小程序- view中多个text换行
Etcd summary mechanism and usage scenarios
逻辑是个好东西
el-form-item 正则验证
Use lambda function URL + cloudfront to realize S3 image back to source
焱融看 | 混合云时代下,如何制定多云策略
Collation and review of knowledge points of Microcomputer Principle and interface technology - pure manual
App自动化测试开元平台Appium-runner
C language course design topic
Journal MySQL
3.4 data query in introduction to database system - select (single table query, connection query, nested query, set query, multi table query)
【IoT毕设.上】STM32+机智云AIoT+实验室安全监控系统