用两个栈模拟一个队列的运算

原题:用两个栈模拟一个队列运算的基本思想是用一个栈作为输入,另一个栈作为输出。进队列时,将数据进入到作为输入的栈中。输出时,如果作为输出的栈已空,则从输入栈将已输入到栈中的所有数据输入到输出栈中,然后由输出栈输出数据;如果作为输出的栈不空,则就从输出栈输出数据。显然,只有在输入、输出栈均为空时队列才空。

程序如下:

#include<iostream.h>
#include<stdlib.h>
#include<time.h>
#define INIT_SIZE 100//存储空间初始分配量
#define INCREMENT 10//存储空间分配增量
#define ElemType char

typedef struct 
{
	ElemType *base;//在栈构造之前和销毁之后,base值为NULL
	ElemType *top;//栈顶指针
	int stacksize;//当前已分配的存储空间,以元素为单位
}SqStack;

typedef struct 
{
	SqStack S1;
	SqStack S2;
}DSQueue;

int InitStack(SqStack &S)
{//构造一个空栈
	S.base=new ElemType[INIT_SIZE];
	if(S.base == NULL)
	{//溢出
		cout<<"存储空间分配失败!"<<endl;return -1;
	}
	S.top=S.base;//S.top=S.base表示为空栈
	S.stacksize=INIT_SIZE;//为栈容量赋初值
	return 1;
}

int Pop(SqStack &S,ElemType &e)
{//如栈非空,则删除栈顶元素
	if(S.base == S.top)
	{//栈空条件
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
以下是利用两个s1和s2来模拟一个队列的C语言代码: ``` #include <stdio.h> #include <stdlib.h> #define MAXSIZE 100 typedef struct { int data[MAXSIZE]; int top; } Stack; void initStack(Stack *s) { // 初始化 s->top = -1; } void push(Stack *s, int x) { // 入操作 if (s->top == MAXSIZE-1) { printf("Stack Overflow!\n"); return; } s->top ++; s->data[s->top] = x; } int pop(Stack *s) { // 出操作 if (s->top == -1) { printf("Stack Underflow!\n"); return -1; } int x = s->data[s->top]; s->top --; return x; } int getTop(Stack *s) { // 获取顶元素 if (s->top == -1) { printf("Stack Underflow!\n"); return -1; } int x = s->data[s->top]; return x; } int isEmpty(Stack *s) { // 判断是否为空 return s->top == -1; } typedef struct { Stack s1; Stack s2; } Queue; void initQueue(Queue *q) { // 初始化队列 initStack(&q->s1); initStack(&q->s2); } void inqueue(Queue *q, int x) { // 入队操作 push(&q->s1, x); } int outqueue(Queue *q) { // 出队操作 if (isEmpty(&q->s1) && isEmpty(&q->s2)) { printf("Queue Underflow!\n"); return -1; } if (isEmpty(&q->s2)) { // 如果s2为空,则将s1中的元素全部倒入s2中 while (!isEmpty(&q->s1)) { int x = pop(&q->s1); push(&q->s2, x); } } int x = pop(&q->s2); // 此时s2的顶元素即为队列头部元素 return x; } int queue_empty(Queue *q) { // 判断队列是否为空 return isEmpty(&q->s1) && isEmpty(&q->s2); } int main() { Queue q; initQueue(&q); inqueue(&q, 1); inqueue(&q, 2); inqueue(&q, 3); printf("%d\n", outqueue(&q)); // 输出队列头部元素1 inqueue(&q, 4); printf("%d\n", outqueue(&q)); // 输出队列头部元素2 printf("%d\n", outqueue(&q)); // 输出队列头部元素3 printf("%d\n", outqueue(&q)); // 输出队列头部元素4 printf("%d\n", outqueue(&q)); // 队列为空,输出-1(队列下溢) return 0; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Storm-Shadow

你的鼓励将是我最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值