使用堆栈类实现列表类

Implementing List class with using Stack class

本文关键字:实现 列表 堆栈      更新时间:2023-10-16

我正在尝试编写像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 类型是变量类所必需的。如何实现这两个功能?

假设您的堆栈仅公开PushPop函数,那么您将无法有效地实现具有索引的列表。

如果您以普通C++样式编程,那么基本数据结构将是动态数组或链表。然后,您可以在这些堆栈之上构建堆栈。但请注意,链表中的索引会很慢(线性时间复杂度)。

如果你以函数式风格编程,那么基本结构是"list",它是一个不可变的单链表,它实际上与不可变堆栈相同。但同样,与之索引会很慢。


另请注意,您的Stack实现不正确:您正在为单个T分配内存,但随后您假设您可以将其用于无限数量的T。你要么需要走链表路线:为每个项目分配一个新节点,并用指针连接节点;或者你需要走动态数组路线:分配一个一定大小的数组,当它变得太小时,重新分配它。