Implementation of the task using the c++stack

Task: divide the stack into 2 stacks. One has even numbers, the other has odd numbers. I got confused with the implementation of the function of viewing the top of the stack with extraction. Tell me where I went wrong.

#include <iostream>

using namespace std;
struct Stack{
    int info;

    Stack* head;
}*b,*t;
struct EvenStack {
    int info;
    EvenStack* head;
}*begin1,*t1;
struct OddStack {
    int info;
    OddStack* head;
}*begin2,*t2;


Stack* push(Stack* p, int n) {
    Stack* t = new Stack;
    t->info = n;
    t->head = p;
    return t;
}
int View( Stack* p, int n) {
    int temp = t->info;
    p = p->head;
    delete t;
    return temp;
}


EvenStack* pushEven(EvenStack *p, int n) {
    EvenStack* t1 = new EvenStack;
    t1->info = n;
    t1->head = p;
    return t1;
}
OddStack* pushOdd(OddStack* p, int n) {
    OddStack* t2 = new OddStack;
    t2->info = n;
    t2->head = p;
    return t2;
}
void OddPrint(OddStack *begin2) {
    cout << "Odd Stack: ";
    OddStack* r = begin2;
    while (r != NULL) { cout << r->info << " "; r = r->head; }
}
void EvenPrint(EvenStack* begin1) {
    cout << "Even Stack: ";
    EvenStack* r = begin1;
    while (r != NULL) { cout << r->info << " "; r = r->head; }
}
int main()
{
    setlocale(0, "");
    int n=0, k, i = 0;
    cout << "Введите количество элементов: ";
    cin >> k;
    cout <<"Введите элементы: "<<endl;
    while (i < k) {
        cin >> n;
        b =push(b,n);
        cout << "Положили в стек:" <<n<< endl;
        i++;
    }
    while (t != NULL) {
       int x = View(b,n);
       if (x % 2 == 0) { begin2 = pushOdd(begin2, x); cout << "Положили в чётный стек:" << x << endl; }
       else { begin1 = pushEven(begin1, x); cout << "Положили в нечётный стек:" << x << endl;
       };

    }
    EvenPrint(begin1);
    OddPrint(begin2);
}
Author: Andrey Oleshkevich, 2020-03-25

1 answers

Your problem is that you are trying to solve the same problem three times. Most likely, when writing the code, you felt that you were repeating the code (perhaps you even used ctrl+c ctrl+v). Repeating the code is an important signal that you are doing something wrong and you need to stop and think again about solving the problem.


I understand that you want to create two stacks - one with even numbers and the other with odd numbers. What is a stack?

Stack (English stack-stack; stack read) is an abstract data type that is a list of elements organized according to the LIFO principle (last in , first out)

In our case, the important thing is that the stack is an entity that does not depend on the type of elements. (Indeed, the definition does not say what type the elements should be). There is no defined separate stack for strings, a separate stack for integers, or a separate stack for even integers. There is just a stack that has the elements can be either strings, integers, etc.

You tried to create a separate stack for even numbers and a separate stack for odd numbers. I suggest creating a stack, and then (depending on your needs) putting everything you need there.


Implementing a simple stack for integers:

#include <iostream>
using namespace std;

//структура - элемент стека
struct StackItem
{
    StackItem* next = nullptr;  //хранит указатель на следующий элемент
    int data;
};

//добавляем новый элемент на вершину стека
StackItem* push(StackItem* top, int var)
{
    StackItem* new_top = new StackItem;
    new_top->data = var;
    new_top->next = top;
    top = new_top;
    return top;
}

//удаляем вершину стека и возвращаем значение.
StackItem* pop(StackItem* top)
{
    if (top == nullptr)     return 0;

    auto old_top = top;
    top = old_top->next;    //теперь вершина - следующий элемент
    delete old_top;
    return top;
}

void print(StackItem* top)
{
    auto iter = top;
    while (iter != nullptr) //если iter == nullptr - дошли до конца стека
    {
        std::cout << iter->data << ' '; 
        iter = iter->next;  //вывели значений, переходим к следующему элементу
    }
    std::cout << '\n';
}

int main()
{
    StackItem* top = nullptr;
    top = push(top, 5);
    print(top);

    top = pop(top);
    print(top);
}

The stack element - StackItem stores data (int) and a pointer to the next element. The basic functions of working with such a stack - push and pop-are implemented. I advise you to understand the code. Now, if necessary, you can create two stacks:

StackItem *oddTop = nullptr, eventTop = nullptr;
oddTop = push(oddTop, 5);     //помещаем нечетные
eventTop = push(eventTop, 4); //помещаем четные

Both odd and even numbers are integers and easily fall into the int type. However, our stack still turned out to be dependent on the type of elements (for example, you can't put a string in it).


If you solve the problem further, you can move away from binding to the type by adding templates.

template <typename T>   //объявили шаблон с именем типа T
struct StackItem
{
    StackItem<T>* next = nullptr;   //хранит указатель на следующий шаблонный элемент типа StackItem<T>
    T data; //хранит элемент типа T
};

template <typename T>
StackItem<T>* push(StackItem<T>* top, const T& var) //добавили шаблонную функцию push
{
    StackItem<T>* new_top = new StackItem<T>;
    new_top->data = var;
    new_top->next = top;
    top = new_top;
    return top;
}

StackItem<int>* int_stack;     //стек, где элементами являются  целочисленные значения
StackItem<double>* double_stack; 
StackItem<std::string>* string_stack;

push(int_stack, 5);
push(string_stack, "Hello");

In the code above, we "untied" the type in StackItem and in the push function. Now they will work for all types(with reservations). During compilation, template methods and classes are instantiated (=substituted), i.e. the compiler looks at which types are used for template methods and generates the required code. We use the StackItem class for int, double, and string types - the compiler will create code for three classes and substitute int, double, and string instead of 'T'. An additional code for the push function for int and string types will also be created (for double, no code will be created, because we did not call it the corresponding push method).

The next iteration will be to create a Stack class that will store a pointer to the vertex (StackItem) and have methods push, pop, display, and so on

 1
Author: 232_159, 2020-03-30 06:32:10