我正在尝试使用一组堆栈来实现堆栈。每个堆栈都有一个最大大小(阈值),每次达到此大小(即当前堆栈已满)时,我都会传递到下一个堆栈。这种机制对用户应该是透明的,它应该像一个单片堆栈一样。
我想用一叠纸叠。这是我的单个堆栈类,实现为单链列表。
#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)
的调用未执行应做的事情。第一个(并且仅在此示例中)内部堆栈保持为空,我不知道为什么。
感谢您的帮助!