c++ - C++ 堆栈堆栈
问题描述
我正在尝试使用一组堆栈来实现一个堆栈。每个栈都有一个最大大小(阈值),每次达到这个大小(即当前栈满),我就传给下一个。这种机制对用户应该是透明的,它应该表现为一个单一的堆栈。
我想用一堆堆栈。这是我的单栈类,实现为单链表。
#include <iostream>
template <typename T>
class Node
{
public:
T data;
Node<T> *next;
Node(T data, Node<T> *next = nullptr)
{
this->data = data;
this->next = next;
}
};
template <typename T>
class Stack
{
Node<T> *head;
public:
Stack()
{
head = nullptr;
}
bool IsEmpty()
{
return head == nullptr;
}
void push(T data)
{
if (IsEmpty())
{
head = new Node<T>(data);
}
else
{
head = new Node<T>(data, head);
}
}
T peek()
{
if (IsEmpty())
{
throw std::runtime_error("peek : stack empty");
}
return head->data;
}
T pop()
{
if (IsEmpty())
{
throw std::runtime_error("pop : stack empty");
}
T data = head->data;
head = head->next;
return data;
}
void print()
{
std::cout << "stack : ";
if (IsEmpty())
{
std::cout << "empty" << std::endl;
return;
}
Node<T> *p = head;
while (p != nullptr)
{
std::cout << p->data << " ";
p = p->next;
}
std::cout << std::endl;
}
};
这就是我实现堆栈类的方式。
#include <iostream>
#include "stack.hpp"
template <typename T>
class SetOfStacks
{
private:
Stack<Stack<T>> stacks;
int threshold;
int StackSize;
public:
SetOfStacks()
{
stacks.push(Stack<T>());
threshold = 4;
StackSize = 0;
}
void push(T data)
{
if (StackSize == threshold)
{
stacks.push(Stack<T>());
StackSize = 0;
}
stacks.peek().push(data);
StackSize++;
}
bool IsEmpty()
{
return stacks.peek().IsEmpty();
}
void print()
{
stacks.peek().print();
}
T peek()
{
return stacks.peek().peek();
}
T pop()
{
/* ... */
}
};
int main()
{
try
{
SetOfStacks<int> stack;
stack.print(); // --> stack empty, OK!
for (int i = 0; i < 4; i++)
{
stack.push(i);
}
stack.print(); // --> still stack empty, why?
}
catch (const std::exception &exc)
{
std::cerr << exc.what() << std::endl;
}
return 0;
}
问题是调用stack.push(i)
没有做它应该做的事情。第一个(并且仅在这个例子中)内部堆栈仍然是空的,我不知道为什么。
谢谢你的帮助!
解决方案
推荐阅读
- apache-spark - 如果某些条件满足 spark 中的每个组,则向列添加值
- javascript - 有条件地为 requestAnimationFrame 安排任务的理想方法(使用 fastdom)
- angular - 在angular+ spring boot中上传50MB文件的最佳实践是什么
- php - 将 Composer 客户端库添加到 PHP 容器
- reactjs - TypeScript 没有选择重载
- excel - Excel Solver - 限制变量数
- blazor-webassembly - 带有 Enter 按钮的 Blazor InputText 触发函数
- python-3.x - 如何在类中使用 Python 的 websockets 和 asyncio 以及现有的事件循环
- matlab - Matlab:如何将“日期时间”数据导出到外部文件?“使用 fprintf 时出错。没有为‘单元’输入定义函数。”
- oracle - 如何在 SQL plus 中的列值之前修剪尾随空格