【发布时间】:2020-09-10 12:01:40
【问题描述】:
我正在尝试制作类似队列或堆栈的结构,我可以在其中向底部和顶部添加和删除 int 数字。
如果输入 int 为偶数(%2 = 0),则将其添加到顶部,如果为奇数(%2 = 1),则将其添加到底部。
我试图使用只有数据和下一个(指向下一个节点对象的指针)的 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;
}
}
}
【问题讨论】:
-
这看起来像是出于教育目的,所以这不会立即提供帮助,但
std::deque。 -
建议:1:别再想ins stack了。只要您可以在两端进行操作,您就没有堆栈。你需要不同的想法。一方面,您需要两种推送方法,一种用于顶部,一种用于底部。或者因为我们试图不以堆栈的方式思考,一个用于前端,一个用于后端。您还需要两个 pops.2:编写此类并在担心应用程序逻辑之前对其进行测试,一方面是偶数,另一方面是赔率。如果你构建你的 staque,让它只做你现在需要它做的事情,那么以后重用它会更加困难。
-
3:进一步分解。编写一个并测试一个通用链表,它可以完成所有常见的链表工作并编写 staque 以便它使用链表。现在您有了一个链表、一个 staque 和一个在一端添加偶数并在另一端添加赔率的工具。
-
一般建议:从计划开始。问问自己,“我需要做什么?”然后写下你的答案。将答案分解为步骤。将这些步骤分解为步骤。继续前进,直到您拥有一组可以轻松编写和组装到程序中的小构建块。如果你不知道怎么做,就把它变成一堆小问题,然后攻击小问题。如果你发现你必须在许多步骤中做同样的事情,那就概括它,让每个人都使用同样的东西。有人已经写过的小步骤,赔率真的很好。
-
你有一个double-ended queue。