链式存储结构实现栈C++实现

每次入栈操作相当于在链表的头部插入元素

#include<iostream>

using namespace std ;
#define ElemType int
struct Stacklist
{
    Stacklist* next;
    ElemType   data;    
};

class Stack
{
    private:
            Stacklist* top ;
    public:
            Stack() ;
            ~Stack() ;
            void InitStack();                
            bool pop(ElemType &e);
            bool push(ElemType e);
            
};
Stack::Stack()
{
    top = new Stacklist[1];
    top->next = NULL ;
}
Stack::~Stack()
{
    delete []top ;
}
bool Stack::pop(ElemType &e)
{

    if(top->next == NULL)
    {
        return false ;
    }
    Stacklist* firstNode ;
    firstNode = top->next ;
    e = firstNode->data ;
    top->next = firstNode->next ;
    delete  []firstNode ;
    return true ;
}

bool Stack::push(ElemType e)
{    
    Stacklist* Node ;
    Node = new Stacklist[1] ;
    Node->data = e ;
    Node->next = top->next ;
    top->next = Node ;
    return true ;
}
int main()
{
    Stack st ;
    int a = 1;

    for(int i = 0 ;i<10;i++)
    {
        st.push(i) ;
    }
    for(int i=0;i<10;i++ )
    {
        st.pop(a);
        cout<<a<<" " ;
    }
    cout<<endl;
    system("pause");
}


猜你喜欢

转载自blog.csdn.net/wx734518351/article/details/80086150