简体   繁体   English

C++ 将偶数压入偶数栈,将奇数压入奇数栈

[英]C++ pushing even numbers in an even stack and odd numbers in an odd stack

I'm trying to verify if the current element is even and push it into an even stack and if not to push it into an odd stack without using the library.我正在尝试验证当前元素是否为偶数并将其推入偶数堆栈,如果不是则在不使用库的情况下将其推入奇数堆栈。 I want to push 6 into the even stack delete it from the first stack using pop and so on我想将 6 推入偶数堆栈,使用 pop 等从第一个堆栈中删除它

| Odd stack| First Stack | | Even stack| 
| -------- |     4       | |     6     |
|    5     |     12      | |     12    |
|    3     |     3       | |     4     |
|          |     5       | |           |
|          |     6       | |           |
#include <conio.h>
#include <fstream>
#include <iostream>

using namespace std;

struct nod {
    int info;
    nod* next;
};

nod* l;
int n;

nod* push(int info, nod* l) {
    nod* aux;
    aux = new nod;
    aux->info = info;
    aux->next = l;
    return aux;
}

nod* pop(nod* l) {
    nod *aux1, *aux2;
    if (l != NULL) {
        aux1 = l;
        aux2 = l->next;
        cout << "\nVoi sterge nodul care contine:" << aux1->info << endl;
        delete aux1;
        return aux2;
    } else {
        cout << "\n Stiva este goala. Nu am ce sa sterg." << endl;
        return NULL;
    }
}

// creating stack
void creare_stiva() {
    nod* a;
    int info;
    ifstream f("in.txt");
    f >> n;
    for (int i = 0; i < n; i++) {
        f >> info;
        l = push(info, l);
    }
}
// displaying stack
void afisare_stiva(nod* a) {
    a = l;
    if (a == NULL)
        cout << "Lista nu exista";
    else {
        cout << "\nElementele listei sunt: ";
        while (a) {
            cout << a->info << " | ";
            a = a->next;
        }
    }
}

int main() {
    creare_stiva();
    afisare_stiva(l);
    cout << endl;
    return 0;
}

I tried testing if the element is odd or even but i don't know how to push it in an even stack and then delete it How do I create 2 stacks, one even and one odd to then put the elements from the first stack and then delete them as I go?我尝试测试元素是奇数还是偶数,但我不知道如何将它推入偶数堆栈然后删除它如何创建 2 个堆栈,一个偶数和一个奇数,然后将第一个堆栈中的元素放入并然后像我go一样删除它们?

void testing() {
    int info;
    while (l) {
        if (l -> info % 2 == 0) {

            l = push(info, l)
            l = l -> next;
        } else {
            l = l -> next;
        }
    }
}

First, create 2 stacks and name them like oddStack and evenStack.首先,创建 2 个堆栈并将它们命名为 oddStack 和 evenStack。 Then check if the number is odd or even.然后检查数字是奇数还是偶数。 If the number is even, push it to evenStack;如果是偶数,就push到evenStack; if the number is odd, push it to oddStack.如果数字是奇数,则将其推送到 oddStack。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM