C ++使用Stacks&队列分开甚至&奇数

时间:2016-04-08 18:17:30

标签: c++

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

我如何显示我的Stack&队列? 我如何在Odd或Even中分离任何队列?

#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 << "\t\t" << q2 << endl;
}

 return 0;
}

1 个答案:

答案 0 :(得分:0)

正如我评论的那样,我假设您需要两个堆栈和两个队列。奇数将转到奇数堆栈容器和奇数队列容器。甚至也会转到偶数堆栈容器和偶数队列容器。

这应该有效:

#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;

}