C++使用堆栈和队列来分隔偶数和奇数

C++ using Stacks & Queues to separate even & odd numbers

本文关键字:分隔 队列 堆栈 C++      更新时间:2023-10-16

我试图在不同的堆栈中实现偶数或奇数&队列。这是我的代码:

如何显示我的Stack&队列如何在任何队列中以奇数或偶数分隔?

#include <iostream>
#include <stack>
#include <queue>
using namespace std;
int main()
{
stack <int> s1;
queue <int> q1;
int num[10]={0};
for(int i = 0; i < 10; i++)
{
    cout << "Enter Number " << i << ": ";
    cin >> num[i];
    s1.push(num[i]);
}
int s2;
int q2;
cout << "In Stack" << "t" << "In Queue" << endl;
while(!q1.empty())
{
    for(int i = 0; i <10; i++)
    {
        if(num[i]%2 == 0)
        {
            s2 = s1.top();
            s1.pop();
        }
        else
        {
            q2 = q1.front();
            q1.pop();
        }
    }
    cout << s2 << "tt" << q2 << endl;
}
 return 0;
}

正如我所评论的,我假设您想要两个堆栈和两个队列。奇数将转到奇数堆栈容器和奇数队列容器。Even将转到偶数堆栈容器和偶数队列容器。

这应该有效:

#include <stack>
#include <queue>
int main()
{
    std::stack<int> MyOddStack;
    std::queue<int> MyOddQueue;
    std::stack<int> MyEvenStack;
    std::queue<int> MyEvenQueue;
    int MyNumbers[10];
    int InNum;
    for (int i = 0; i < 10; i++) // take numbers from user and fill the container, the queue and the stack right away
    {
        std::cout << "Please enter number: " << std::endl;
        std::cin >> InNum;
        MyNumbers[i] = InNum; // put in the container
        if (InNum % 2 == 0) // if even add to even queue and even stack
        {
            MyEvenQueue.push(InNum);
            MyEvenStack.push(InNum);
        }
        else //else, add to odd queue and odd stack
        {
            MyOddQueue.push(InNum);
            MyOddStack.push(InNum);
        }
    }
    // You want to display any of the queues/stacks? 
    // put a for loop
    // use .top() and/or .front() to display
    // use .pop() everytime you display an element so you see the next element
    return 0;
}