用两个队列实现栈

前言

        和上一篇一样是一个数据结构的小作业,不好弄到一块,就分开写了。这个代码还是调了挺久的bug。相信点进来的小伙伴都是学过数据结构的吧,不然也不会点进来,所以队列、栈这些概念就不细说了。这个问题还是挺有意义的吧,不多说了,写快点去背马原。

题目

        已知有两个队列q1和q2,现要求用这两个队列实现-一个栈的功能,写出你的设计思想,并用C/C + +写出栈的Push()和Pop()实现代码。

设计思路

        进行入栈操作即Push()实现时,直接将元素入队(进不为空的队列);进行出栈的操作即Pop()实现时,将当前装元素的队列一个一个出队到另一个队列去,当是最后一个元素时进行判断输出。

实现代码

#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
typedef int ElementType;
typedef struct QNode {
	ElementType Data;
	struct QNode* Next;
}*Queue;
Queue CreateQueue() {
	Queue Q = (Queue)malloc(sizeof(struct QNode));
	Q->Next = NULL;//头节点空置
	return Q;
}
bool IsEmpty(Queue Q) {
	return (Q->Next == NULL);
}
Queue AddQ(Queue Q, ElementType x) {
	Queue p = (Queue)malloc(sizeof(struct QNode));
	p->Data = x;
	p->Next = NULL;
	if (IsEmpty(Q))Q->Next = p;
	else {
		Queue q = Q->Next;
		while (q->Next != NULL)q = q->Next;
		q->Next = p;
	}
	return Q;
}
ElementType DeleteQ(Queue Q) {
	if (IsEmpty(Q)) {
		return 0;
		//printf("队列为空\n");
	}
	else {
		Queue q = Q->Next;
		ElementType x = q->Data;
		Q->Next = q->Next;
		free(q);
		return x;
	}
}
void Push(Queue Q1, Queue Q2, ElementType x) {//入栈操作
	if (IsEmpty(Q1) && IsEmpty(Q2))AddQ(Q1, x);
	if (!IsEmpty(Q1) && IsEmpty(Q2)) AddQ(Q1, x);
	else if (IsEmpty(Q1) && !IsEmpty(Q2))AddQ(Q2, x);
}
void Pop(Queue Q1, Queue Q2) {//出栈操作
	if (IsEmpty(Q1) && IsEmpty(Q2)) {
		printf("栈为空\n");
		return;
	}
	if (!IsEmpty(Q1)) {
		while (!IsEmpty(Q1)) {
			ElementType x = DeleteQ(Q1);
			if (IsEmpty(Q1)) {
				if (IsEmpty(Q2))return;//说明此时的x是最后一个元素
				printf("%d\n", x);
				break;
			}
			AddQ(Q2, x);
		}
	}
	else if (!IsEmpty(Q2)) {
		while (!IsEmpty(Q2)) {
			ElementType x = DeleteQ(Q2);
			if (IsEmpty(Q2)) {
				if (IsEmpty(Q1))return;
				printf("%d\n", x);
				break;
			}
			AddQ(Q1, x);
		}
	}
}
int main() {
	int choice, n;
	ElementType x;
	printf("请输入你想要进行的操作次数:\n");
	scanf("%d", &n);
	Queue Q1 = CreateQueue(), Q2 = CreateQueue();
	printf("请输入你想要进行的操作(1:表示入栈,0:表示出栈):\n");
	while (n--) {
		scanf("%d", &choice);
		if (choice == 1) {
			scanf("%d", &x);
			Push(Q1, Q2, x);
		}
		else if (choice == 0) Pop(Q1, Q2);
	}
	printf("操作结束后栈中的元素依次为:\n");
	while (!(IsEmpty(Q1) && IsEmpty(Q2))) Pop(Q1, Q2);
}

运行结果

结语

        感觉自己真的好弱,参加学校的集训队考核没过,参加校赛的ACM就只A了两题。希望自己能越变越强吧。一起加油!!~~

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

xiaoyuer2815

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

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

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

打赏作者

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

抵扣说明:

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

余额充值