链栈的C++实现

链式结构栈的C++实现,参考书《数据结构》(秦峰,汤亚玲)
代码实现贴一下:

#include 
//链栈
class StackNode{
     
public:
    int data;
    StackNode *next;
    StackNode(){
     
        next = NULL;
    };
};
class LinkStack
{
     
    //链栈的定义
private:
StackNode *top;
public:
    LinkStack(){
     
        top = NULL;
        //构造一个空的栈
    };
    ~LinkStack()
    {
     
        StackNode *p;
        while (top)
        {
     
            p=top;
            top = top->next;
            delete p;
        }
        top =NULL; //栈顶指针为空代表空栈
    }
    int Empty_Stack()
    {
     
        return(!top);
        //空返回1,不空返回0
    };
    int Push(int e){
     
        StackNode *p = new StackNode();
        if(p)
        {
     
            //这里链栈相当于一个没有头结点的链表,每次都用头插法插入新的结点
            p->data = e;
            p->next=top;
            //栈为空栈的时候,p->next是NULL,不空的时候,指向栈顶元素
            top = p;
            return 1;
        }
        else return 0;

    };
    int Pop(int &e){
     
        StackNode *p;
        if(top)
        {
     
            p = top;
            e = p->data;
            top = top->next;
            delete p;
            return 1;
        }
        else return 0;
    };
    int GetTop(int &e){
     
        //取栈顶的元素
         if(top)
         {
     
             e = top->data;
             return 1;
         }
         else return 0;
    }

};

int main() {
     
    
    std::cout << "Hello, World!" << std::endl;
    return 0;
}

你可能感兴趣的:(数据结构,c++,栈)