Staque,堆栈可以将int数也添加到底部和顶部

我正在尝试制作队列或类似堆栈的结构,在其中可以向/从底部和顶部添加和删除整数 如果输入int为偶数(%2 = 0),则将其添加到顶部,如果输入奇数(%2 = 1),则将其添加到底部

我正在尝试使用仅获得数据和next(指向下一个Node对象的指针)的Node类来实现它 但是由于这个原因,我无法在顶部(只能在底部)添加或删除int

多数民众赞成在头文件:

#include <iostream>
using namespace std;

#ifndef myStaque
#define myStaque

class Staque
{
 public:
    Staque();
    Staque(const Staque & a);
    bool ifEmpty() const;
    void push(const int& b);
    void print() const;
    int top() const;
    int bottom() const;
    void delKenti();
    void delLuwi();
    Staque& operator= (const Staque& a);
 private:
    class Node
    {
    public:
        int data;
        Node* next;
        Node* previous;
        Node(int a, Node* c = 0, Node* b = 0): data(a), next(c), previous(b){}
    };
    Node* myTop;
    Node* myBottom;
};
#endif

而且我正在尝试使它工作的cpp(但它不工作):

#include "myStaque.h"
#include <new>
using namespace std;

Staque::Staque()
{

}
Staque::Staque(const Staque& a) {
    *this = a;
}
Staque& Staque:: operator= (const Staque& a) {
    Staque::Node* ptr;
    for (ptr = a.myBottom; ptr != 0; ptr = ptr->next)
    {
        myTop = a.myTop;
        myBottom = a.myBottom;
    }
    return *this;

}

bool Staque::ifEmpty() const
{
    return (myBottom == 0);
}
void Staque::push(const int& b)
{
    if (ifEmpty()) {
        myBottom = new Staque::Node(b, 0);
        myTop = myBottom;
    }
    if (b % 2) {
        Staque::Node* tmp;
        tmp = new Staque::Node(b, 0);
        myTop->next = tmp;
        myTop = tmp;
    }
    else {
        myBottom = new Staque::Node(b, myBottom);
    }

}
void Staque::print() const
{
    Staque::Node* ptr;
    for (ptr = myBottom; ptr != 0; ptr = ptr->next)
        cout << ptr->data << ", ";
    cout << endl;
}
void Staque::delLuwi() {
    if (myBottom->data % 2 && myTop->data % 2) {
        cout << "Bottom and top are kenti " << endl;
    }
    else {
        if (!(myBottom->data % 2)) {
            myBottom = myBottom->next;
        }
        else if (!(myTop->data % 2)) {
            Staque::Node* tmp;
            tmp = myBottom;
            while ( !(tmp->next = 0) ) {
                tmp = tmp->next;
            }
            myTop = tmp;
            myTop->next = 0;
        }
    }
}
void Staque::delKenti() {
    if (!(myBottom->data % 2) && !(myTop->data % 2)) {
        cout << "Bottom and top are kenti " << endl;
    }
    else {
        if (myBottom->data % 2) {
            myBottom = myBottom->next;
        }
        else if (myTop->data % 2) {
            Staque::Node* tmp;
            tmp = myBottom;
            while (!(tmp = nullptr)) {
                tmp = tmp->next;
            }
            myTop = tmp;
            myTop->next = 0;
        }
    }
}
评论