• C++链式栈


    LinkStack:

    //链式栈
    #include<iostream>
    using namespace std;
    typedef int elemType;
    
    typedef struct StackNode
    {
        elemType data;
        StackNode *next;
    }*LinkList;
    
    struct LinkStack
    {
        LinkList top;
        int count;
    };
    
    //初始化
    void InitStack(LinkStack *S)
    {
        S->top = NULL;
        S->count = 0;
    }
    
    //判断是否为空
    bool EmptyStack(LinkStack *S)
    {
        if(S->count==0)
            return true;
        else
            return false;
    }
    
    //进栈
    void Push(LinkStack *S, elemType e)
    {
        LinkList p = new StackNode;
        p->data = e;
        p->next = S->top;
        S->top = p;
        S->count++;
    }
    
    //出栈
    void Pop(LinkStack *S, elemType *e)
    {
        LinkList p = new StackNode;
        if(EmptyStack(S))
            cout<<"出错,栈已为空."<<endl;
        *e = S->top->data;
        p = S->top;
        S->top = p->next;
        delete p;
        S->count--;
    }
    
    //获取栈顶元素
    int GetTop(LinkStack *S)
    {
        if(S->count==0)
            cout<<"无法获取,栈为空."<<endl;
        elemType e;
        e = S->top->data;
        return e;
    }
    
    void TraStack(LinkStack *S)
    {
        if(S->count==0)
            cout<<"栈为空."<<endl;
        LinkList p = S->top;
        int i = 1;
        while(p!=NULL)
        {
            cout << i <<":	"<< p->data<<endl;
            p = p->next;
            i++;
        }
    }
    
    //清空栈
    bool ClearStack(LinkStack *S)
    {
        if(S->count==0)
        {
            cout<<"栈已为空,无需清空."<<endl;
            return false;
        }
        int num = S->count;
        while(num>=0)
        {
            LinkList p = new StackNode;
            p = S->top;
            if(num==0)
            {
                S->top = NULL;
                S->count = 0;
            }
            else
            {
                S->top = p->next;
            }
            delete p;
            num--;
        }
        return true;
    }
    
    int main()
    {
        LinkStack s;
        InitStack(&s);
        for(int i=1;i<7;i++)
            Push(&s,i);
        TraStack(&s);
        cout<<endl;
    
        elemType x = GetTop(&s);
        cout<<"栈顶元素为: "<< x <<endl;
        elemType i=0;;
        Pop(&s, &i);
        cout<<"删除栈顶元素后栈为:"<<endl;
        TraStack(&s);
        cout<<endl;
    
        ClearStack(&s);
        cout<<"清空栈..."<<endl;
        TraStack(&s);
        if(EmptyStack(&s))
            cout <<"栈已经为空!"<<endl;
        cout<<endl;
    
        return 0;
    }
  • 相关阅读:
    jvm类加载
    SpringMVC拦截器踩坑日记
    ConcurrentHashMap源码
    HashMap源码
    Linux搭建数据质量监控 Griffin
    那些说代码管理不方便的,我估计是你不会用git(Git源码管理)
    VS2019 开发AngularJS(TypeScript)代码缩进处理
    Arraylist和Map哪个性能更好
    dynamics crm 团队及团队模板
    无法加载文件或程序集 PublicKeyToken=null'或其依赖之一,需要强名称的程序集
  • 原文地址:https://www.cnblogs.com/jx-yangbo/p/4857663.html
Copyright © 2020-2023  润新知