使用堆栈类实现列表类
Implementing List class with using Stack class
我正在尝试编写像Python这样的解释型编程语言,所以我需要一个List类来存储函数和变量的"地址"。我实现了用于实现列表类的堆栈类:
typedef unsigned int UIntegerP; //This type for storing addresses
#define Free 0x0
template <typename T> class Stack{
public:
unsigned long UsedBSize; // You can use that like End Of Stack (EOS)
Stack(void){
this->BSize = 0; this->UsedBSize = 0;
this->Buffer = new T;
}
~Stack(void){
delete this->Buffer;
}
inline void Push(T Variable){
if(this->UsedBSize == this->BSize){
this->BSize++;
} this->Buffer[this->UsedBSize] = Variable; this->UsedBSize++;
}
inline T Pop(bool IsProtected = false){
if(IsProtected){
return this->Buffer[this->UsedBSize];
}else{
this->UsedBSize--; T Element = this->Buffer[this->UsedBSize]; this->Buffer[this->UsedBSize] = Free;
return Element;
}
}
private:
T *Buffer;
unsigned long BSize;
};
这就是我想要实现的类:
class List{
private:
Stack<UIntegerP> *stack = new Stack<UIntegerP>; //A stack for storing variable addresses
public:
~List(void){
delete this->stack;
}
List(Stack<UIntegerP> Elements){
while(Elements.UsedBSize != 0){
this->stack->Push(Elements.Pop());
}
}
List(Stack<UIntegerP> *Elements){
while(Elements->UsedBSize != 0){
this->stack->Push(Elements->Pop());
}
}
UIntegerP Get(unsigned long Size); //Get Address with Index number
UIntegerP Set(unsigned long Size, UIntegerP Address); //Set Address with Index number
};
我将使用此List类来实现像字典一样的Python。UIntegerP 类型是变量类所必需的。如何实现这两个功能?
假设您的堆栈仅公开Push
和Pop
函数,那么您将无法有效地实现具有索引的列表。
如果您以普通C++样式编程,那么基本数据结构将是动态数组或链表。然后,您可以在这些堆栈之上构建堆栈。但请注意,链表中的索引会很慢(线性时间复杂度)。
如果你以函数式风格编程,那么基本结构是"list",它是一个不可变的单链表,它实际上与不可变堆栈相同。但同样,与之索引会很慢。
另请注意,您的Stack
实现不正确:您正在为单个T
分配内存,但随后您假设您可以将其用于无限数量的T
。你要么需要走链表路线:为每个项目分配一个新节点,并用指针连接节点;或者你需要走动态数组路线:分配一个一定大小的数组,当它变得太小时,重新分配它。
相关文章:
- 使用简单类型列表实现的指数编译时间.为什么
- 为什么在排序链表上的这种合并实现总是将两个列表都设置为 NULL,而只有一个应该设置一个列表?
- 如何理解C++中链表的自由列表实现?
- 嵌套列表,用于在 C++ 中实现邻接列表
- 单链接列表实现,规则为 3
- 如何使用列表/数组在C++中实现 Python "... not in ..."?
- 在给定的项目列表上实现搜索?
- 如何在C / C++中正确实现链接列表而不会使程序崩溃
- 可视化 如何实现 c++ 列表的运算符=?
- 使用邻接列表C++实现 Dijkstra
- 使用初始值设定项列表作为函数参数的类对象实现运算符 [] 的示例
- 如何实现列表:<T>:迭代器?
- C++如何实现列表的数组
- 使用unique_ptr<>实现列表?
- 使用配对模板实现列表模板
- 实现列表迭代器和运算符:--++*
- 如何使用 Win32/WTL 实现列表视图的缩放
- 使用std::experimental::optional来实现列表
- 使用堆栈类实现列表类
- 实现列表:在末尾添加一个节点