您的位置:首页 > 编程语言 > C语言/C++

C++_简单的链表栈

2015-09-12 19:15 441 查看
类中包含一个指针指向栈顶的元素,定义一个结构体,包括值和一个指向他上一个元素的指针。

#include <iostream>
#define NULL 0

using namespace std;

class MyStack
{
private:
    struct node
    {
        int s;
        node *link;
    };
    node *top;
public:
    MyStack()
    {
        top=NULL;
    }
    ~MyStack()
    {
        node *temp;
        while(top)
        {
            temp=top;
            top=temp->link;
            delete temp;
        }
    }
    bool Add(int a);
    bool Delete(int &a);
    inline bool StackEmpty()
    {
        if(top) return false;
        else return true;
    }

};

bool MyStack::Add(int a)
{
    node *temp = new node;
    if(temp)
    {
        temp->link=top;
        temp->s=a;
        top=temp;
        return true;
    }
    else
    {
        cout << "failed" << endl;
        return false;
    }
}

bool MyStack::Delete(int &a)
{
    if(!StackEmpty())
    {
        node *temp;
        temp=top;
        a=temp->s;
        top=temp->link;
        delete temp;
        return true;
    }
    else
    {
        cout << "the stack is empty" << endl;
        return false;
    }
}

int main()
{
    int a;
    MyStack s;
    s.Add(3);
    s.Add(2);
    s.Add(1);
    for(int i=0;i<3;i++)
    {
        s.Delete(a);
        cout << a  << endl;
    }
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: