用栈实现队列

该文介绍了一种利用两个栈实现队列功能的方法。通过在栈一存储元素,当需要出队时,如果栈二为空,则将栈一所有元素转移到栈二,然后从栈二顶部取出元素。代码示例展示了如何初始化、销毁栈以及如何进行压栈、出栈、查看队头元素和判断队列是否为空的操作。
摘要由CSDN通过智能技术生成

在这里插入图片描述

1.思路分析

在这里插入图片描述
栈 先进后出
队列 先进先出
我们创建两个栈
栈一 存放1 2 3 4,出栈为1,可是我们队列出队结果为4,我们可以先将这个栈的数据导入到栈二
在这里插入图片描述

这时我们出栈二,发现出来的是1
从上可知我们只需要将栈一数据导入栈二导出即可

2.代码实现


#include<stdio.h>
#include<stdlib.h>
#include<stdlib.h>
#include<stdbool.h>
#include<assert.h>
typedef int STDatatype;
typedef struct stack
{
	STDatatype* a;
	int top;
	int capacity;
}ST;
void StackInit(ST* ps);
void StackDestroy(ST* ps);
void StackPush(ST* ps, STDatatype x);
void StackPop(ST* ps);
STDatatype StackTop(ST* ps);
bool StackEmpty(ST* ps);
int StackSize(ST* ps);
void StackInit(ST* ps)
{
	assert(ps);
	ps->a = (STDatatype*)malloc(sizeof(STDatatype) * 4);
	if (ps->a == NULL)
	{
		perror("malloc fail");
		exit(-1);
	}
	ps->top = 0;
	ps->capacity = 4;
	
}
void StackDestroy(ST* ps)
{
	assert(ps);
	free(ps->a);
	ps->top = 0;
	ps->capacity = 0;
}
void StackPush(ST* ps, STDatatype x)
{
	assert(ps);
	if (ps->top == ps->capacity)
	{
		STDatatype* tmp = (STDatatype*)realloc(ps->a, ps->capacity * 2 * sizeof(STDatatype));
		if (tmp == NULL)
		{
			perror("malloc");
			exit(-1);
		}
		ps->capacity *= 2;
		ps->a = tmp;
	}
	ps->a[ps->top] = x;
	ps->top++;
	
}
void StackPop(ST* ps)
{
	assert(ps);
	/*assert(ps->top > 0);*/
	assert(!StackEmpty(ps));
	ps->top--;

}
STDatatype StackTop(ST* ps)
{
	assert(ps);
	//assert(ps->top > 0);
	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 pushst;
    ST popst;


} MyQueue;


MyQueue* myQueueCreate() {
    MyQueue*pq=(MyQueue*)malloc(sizeof(MyQueue));
    StackInit(&pq->pushst);//初始化两个站
    StackInit(&pq->popst);
    return pq;
}

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

}
int myQueuePeek(MyQueue* obj);
bool myQueueEmpty(MyQueue* obj);
int myQueuePop(MyQueue* obj) {
    assert(obj);
    assert(!myQueueEmpty(obj));
    int peek=myQueuePeek(obj);
    StackPop(&obj->popst);
    return peek;
    

}

int myQueuePeek(MyQueue* obj) {
    assert(obj);
    assert(!myQueueEmpty(obj));
    if(StackEmpty(&obj->popst))//导入数据
    {
        while(!StackEmpty(&obj->pushst))
        {
            StackPush(&obj->popst,StackTop(&obj->pushst));
            StackPop(&obj->pushst);
        }
    }
    return StackTop(&obj->popst);

}

bool myQueueEmpty(MyQueue* obj) {
    assert(obj);
    return (StackEmpty(&obj->pushst)&&StackEmpty(&obj->popst));

}

void myQueueFree(MyQueue* obj) {
    assert(obj);
    StackDestroy(&obj->pushst);
    StackDestroy(&obj->popst);
    free(obj);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值