前言
和上一篇一样是一个数据结构的小作业,不好弄到一块,就分开写了。这个代码还是调了挺久的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了两题。希望自己能越变越强吧。一起加油!!~~