• 链表栈


    #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;
    }
    
            

    类模版实现链表栈,作业,记录一下,以备以后参考。
  • 相关阅读:
    SpringBoot连接数据库
    String、StringBuffer、StringBulider的区别和解析
    异常This application has no explicit mapping for /error
    node使用
    JS总结defer与async(一)
    前端项目搭建与知识框架
    git ssh配置总结
    JS算法
    JS数据结构
    Http与Http2与Https区别和联系
  • 原文地址:https://www.cnblogs.com/pojdd/p/7742193.html
Copyright © 2020-2023  润新知