繁体   English   中英

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

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

我正在尝试验证当前元素是否为偶数并将其推入偶数堆栈,如果不是则在不使用库的情况下将其推入奇数堆栈。 我想将 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;
}

我尝试测试元素是奇数还是偶数,但我不知道如何将它推入偶数堆栈然后删除它如何创建 2 个堆栈,一个偶数和一个奇数,然后将第一个堆栈中的元素放入并然后像我go一样删除它们?

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

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

首先,创建 2 个堆栈并将它们命名为 oddStack 和 evenStack。 然后检查数字是奇数还是偶数。 如果是偶数,就push到evenStack; 如果数字是奇数,则将其推送到 oddStack。

暂无
暂无

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

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