c++自己实现栈 (不调用已有api)

//文件名 my_stack.h
#ifndef _MY_STACK_H
#define _MY_STACK_H

template <typename T>
struct my_node{
    T val;
    my_node<T> * prev;
    my_node<T> * next;
    my_node():prev(NULL), next(NULL){}
    my_node(const T & v):val(v),  prev(NULL), next(NULL){}
    my_node(const T & v, my_node<T> * p, my_node<T> * n):val(v), prev(p), next(n){}
};

template <typename T>
class my_stack{
private:
    my_node<T> guard;
    my_node<T> * stack_top;
public:
    my_stack(){
        stack_top = &guard;
    }
    ~my_stack(){
        while (!empty()){
            pop();
        }
    }
    bool empty(){
        return guard.next == NULL;
    }
    void push(const T & other){
        stack_top->next = new my_node<T>(other, stack_top, NULL);
        stack_top = stack_top->next;
    }
    T top(){
        if(!empty())
            return stack_top->val;
        perror("stack empty!!!");
    }
    void pop(){
        if(!empty()){
            my_node<T> * temp = stack_top;
            stack_top = stack_top->prev;
            stack_top->next = NULL;
            delete temp;
        }
        else
            perror("stack empty!!!");
    }
};


#endif //_MY_STACK_H
posted @ 2022-04-19 18:16  enbug  阅读(33)  评论(0编辑  收藏  举报