• 链表栈


    #include<iostream>
    #include<cstdlib>
    using namespace std;
    
    template <class T>
    struct node
    {
        T data;
        node *next;
    };
    
    template <class T>
    class listack
    {
        node<T> *head;
    public:
        listack()
        {
            head=NULL;
            cout<<"栈初始化"<<endl;
        }
        bool push(T a)
        {
            node<T> *p;
            if(head==NULL)
            {
                p=new node<T>;
                if(p==NULL)return false;
                p->data=a;
                p->next=NULL;
                head=p;
                return true;
            }
            p=new node<T>;
            if(p==NULL)return false;
            p->data=a;
            p->next=head;
            head=p;
            return true;
        }
        bool pop(T &a)
        {
            node<T> *p;
            if(head==NULL)return false;
            a=head->data;
            p=head;
            head=head->next;
            free(p);
            return true;
        }
        bool is_empty()
        {
            if(head==NULL)
                return true;
            else 
                return false;
        }
        ~listack()
        {
            cout<<"栈释放"<<endl;
            if(head==NULL)return;
            node<T> *p;
            p=head;
            head=head->next;
            while(head!=NULL)
            {
                free(p);
                p=head;
                head=head->next;
            }
            free(p);
        }
    };
    
    int main()
    {
        listack <char> a;
        if(a.is_empty())cout<<"栈为空"<<endl;
        else cout<<"栈不为空"<<endl;
        a.push('a');
        a.push('b');
        a.push('c');
        a.push('d');
        a.push('e');
        cout<<"a b c d e 入栈"<<endl;
        char te;
        if(a.is_empty())cout<<"栈为空"<<endl;
        else cout<<"栈不为空"<<endl;
        while(a.pop(te))
        {
            cout<<te<<" ";
        }
        cout<<endl;
        if(a.is_empty())cout<<"栈为空"<<endl;
        else cout<<"栈不为空"<<endl;
        a.~listack();
        system("pause");
        return 0;
    }
    
            

    类模版实现链表栈,作业,记录一下,以备以后参考。
  • 相关阅读:
    郑码
    AutoCAD 安装
    China Mobile 移动
    CCB 建行
    Word基础
    Java 继承
    Java 封装(内部类)
    Java 类与对象
    Java 方法
    Java 数组
  • 原文地址:https://www.cnblogs.com/pojdd/p/7742193.html
Copyright © 2020-2023  润新知