[英]Implementing List class with using Stack class
我正在嘗試編寫像Python這樣的解釋型編程語言,因此我需要一個List類來存儲“地址”函數和變量。 我實現了用於實現List類的Stack類:
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 ++風格進行編程,則基本數據結構將是動態數組或鏈表 。 然后,您可以在其上構建堆棧。 但是請注意,在鏈表中建立索引的速度會很慢(線性時間復雜度)。
如果您以功能性風格進行編程,則基本結構是“列表”,它是一個不可變的單鏈接列表,實際上與不可變的堆棧相同。 但是同樣,用它建立索引將很慢。
還要注意,您的Stack
實現不正確:您正在為單個T
分配內存,但隨后您假定可以將其用於無限多個T
您要么需要執行鏈表路由,要么為每個項目分配一個新節點,然后將這些節點與指針連接; 或者您需要使用動態數組路線:分配一定大小的數組,當數組變得太小時,重新分配它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.