【2023王道数据结构】【栈、队列和数组—page85—03】C、C++完整实现(可直接运行)

【2023王道数据结构】【栈、队列和数组—page85—03】C、C++完整实现(可直接运行),第1张

~~~笔锋至此又怎能平淡而终,故事开始便不承认普通✌✌✌

如果需要完整代码可以关注下方公众号,后台回复“代码”即可获取,阿光期待着您的光临~


题目及题解持续更新中
【2023王道数据结构目录】课后算法设计题C、C++代码实现完整版大全


题目:

利用两个栈s1,s2来模拟一个队列,已知栈的4各运算定义如下:

解题思路:

>由于栈与队列出入相反
>所以利用两个栈可以实现队列
>将所有元素压入s1栈中,然后再压入s2中即可实现逆序

代码实现:

#include 
using namespace std;
#define MAXSIZE 3

//定义循环队列
typedef struct
{
    int data[MAXSIZE];
    int front = 0, rear = 0;
} SqQueue;

//定义栈
typedef struct
{
    int data[MAXSIZE];
    int top1 = -1;
} Stack;

//判断栈是否为空
bool StackEmpty(Stack s)
{
    if (s.top1 == -1)
    {
        return true;
    }
    return false;
}

//判断栈是否溢出
bool StackOverflow(Stack s)
{
    if (s.top1 >= MAXSIZE)
    {
        return true;
    }
    return false;
}

//压栈
void Push(Stack &s, int x)
{
    if (!StackOverflow(s))
    {
        s.data[++s.top1] = x;
    }
    else
    {
        cout << "当前栈已满" << endl;
    }
}

//d栈
void Pop(Stack &s, int &x)
{

    if (StackEmpty(s))
    {
        cout << "当前栈已空" << endl;
        return;
    }
    else
    {
        x = s.data[s.top1--];
    }
}

//入队
void Enqueue(Stack &s1, Stack &s2, int x)
{
    //如果栈s1没有满,将x压入x1
    if (!StackOverflow(s1))
    {
        Push(s1, x);
        return;
    }
    //如果s1满了,同时s2不是空的,表明此时队列已满
    else if (StackOverflow(s1) && !StackEmpty(s2))
    {
        cout << "当前队列已满" << endl;
        return;
    }
    //如果s1满,此时s2为空,队列不满,将s1中元素压入s2
    else if (StackOverflow(s1) && StackEmpty(s2))
    {
        int value;
        while (!StackEmpty(s1))
        {
            Pop(s1, value);
            Push(s2, value);
        }
        Push(s1, x);
    }
}

//出队
void Dequeue(Stack &s1, Stack &s2, int &x)
{
    //如果栈s2不空,直接出队
    if (!StackEmpty(s2))
    {
        Pop(s2, x);
    }
    //如果栈s2空且s1为空,表明队列为空
    else if (StackEmpty(s1))
    {
        cout << "当前队列为空" << endl;
        return;
    }
    //如果栈s2空且s1不空,将s1中元素d出压入s2中
    else
    {
        int value;
        while (!StackEmpty(s1))
        {
            Pop(s1, value);
            Push(s2, value);
        }
        Pop(s2, x);
    }
}

//判断队列是否为空
void QueueEmpty(Stack s1, Stack s2)
{
    if (StackEmpty(s1) && StackEmpty(s2))
    {
        cout << "当前队列为空" << endl;
    }
}

int main()
{
    Stack s1, s2;
    int x = 0;
    QueueEmpty(s1, s2);
    Enqueue(s1, s2, 1);
    Enqueue(s1, s2, 2);
    Dequeue(s1, s2, x);
    cout << x << endl;
    Enqueue(s1, s2, 3);
    Dequeue(s1, s2, x);
    cout << x << endl;
    Dequeue(s1, s2, x);
    cout << x << endl;
    QueueEmpty(s1, s2);
}

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/866755.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-12
下一篇 2022-05-12

发表评论

登录后才能评论

评论列表(0条)

保存