Y_yyico 2022-05-16 19:45
浏览 19
已结题

堆栈模拟队列(数据结构)

问题遇到的现象和发生背景
问题相关代码,请勿粘贴截图

设已知有两个堆栈S1和S2,请用这两个堆栈模拟出一个队列Q。

所谓用堆栈模拟队列,实际上就是通过调用堆栈的下列操作函数:

int IsFull(Stack S):判断堆栈S是否已满,返回10int IsEmpty (Stack S ):判断堆栈S是否为空,返回10void Push(Stack S, ElementType item ):将元素item压入堆栈S;
ElementType Pop(Stack S ):删除并返回S的栈顶元素。

实现队列的操作,即入队void AddQ(ElementType item)和出队ElementType DeleteQ()。
输入格式:

输入首先给出两个正整数N1和N2,表示堆栈S1和S2的最大容量。随后给出一系列的队列操作:A item表示将item入列(这里假设item为整型数字);D表示出队操作;T表示输入结束。
输出格式:

对输入中的每个D操作,输出相应出队的数字,或者错误信息ERROR:Empty。如果入队操作无法执行,也需要输出ERROR:Full。每个输出占1行。

运行结果及报错内容

ERROR:Empty
0
ERROR:Empty
0
ERROR:Empty
0
ERROR:Empty
0
ERROR:Empty
0
ERROR:Empty
0
ERROR:Empty
0

我的解答思路和尝试过的方法
我想要达到的结果

ERROR:Full
1
ERROR:Full
2
3
4
7
8
ERROR:Empty

#include<stdio.h>
#include<malloc.h>
#include<string.h>
#include<math.h>
typedef int ElementType;
struct stack{
    ElementType *Data;
    int top;
    int MaxSize;
};
typedef struct stack *Stack;
Stack S1;
Stack S2;
int IsFull(Stack S)
{
    if(S->top==S->MaxSize-1)return 1;
    return 0;
}
int IsEmpty(Stack S)
{
    if(S->top==-1)return 1;
    return 0;
}
void Push(Stack S,ElementType item)
{
    if(IsFull);
    else S->Data[++S->top]=item;
}
ElementType Pop(Stack S)
{
    if(IsEmpty)return 0;
    return S->Data[S->top--];
}
void AddQ(ElementType item)
{
    if(!IsFull(S1)){
        Push(S1,item);
    }else{
        if(IsEmpty(S2)){
            while(S1->top!=-1)
                Push(S2,S1->Data[S1->top--]);
            Push(S1,item);
        }else{
            printf("ERROR:FULL\n");
        }
    }
}
ElementType DeleteQ()
{
    if(!IsEmpty(S2)){
        return S2->Data[--S2->top];
    }else{
        if(IsEmpty(S1)){
            printf("ERROR:Empty\n");
            return ;
        }else{
            while(S1->top!=-1)
             Push(&S2,S1->Data[S1->top--]);
            return S2->Data[S2->top--];
        }
    }
}
int main()
{
    int N1,N2,a,t;
    scanf("%d %d",&N1,&N2);
    getchar();
    if(N1>N2){
        t=N1;
        N1=N2;
        N2=t;
    }
    //N1--;N2--;
    S1=(Stack)malloc(sizeof(struct stack));
    S2=(Stack)malloc(sizeof(struct stack));
    S1->top=-1;
    S1->MaxSize=N1;
    S1->Data=(ElementType *)malloc(N1*sizeof(ElementType));
    S2->top=-1;
    S2->MaxSize=N2;
    S2->Data=(ElementType *)malloc(N2*sizeof(ElementType));
    char ch;
    scanf("%c",&ch);
    while(ch!='T'){
        getchar();
        if(ch=='A'){
            scanf("%d",&a);
            getchar();
            AddQ(a);    
        }else if(ch=='D'){
            printf("%d\n",DeleteQ());
        }
        scanf("%c",&ch);
    }
    return 0;
}

  • 写回答

0条回答 默认 最新

    报告相同问题?

    问题事件

    • 系统已结题 5月24日
    • 创建了问题 5月16日

    悬赏问题

    • ¥20 有关区间dp的问题求解
    • ¥15 多电路系统共用电源的串扰问题
    • ¥15 slam rangenet++配置
    • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
    • ¥15 对于相关问题的求解与代码
    • ¥15 ubuntu子系统密码忘记
    • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
    • ¥15 保护模式-系统加载-段寄存器
    • ¥15 电脑桌面设定一个区域禁止鼠标操作
    • ¥15 求NPF226060磁芯的详细资料