堆栈的基本操作

#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;
///堆栈的基本结构
typedef struct Stack{
    int data;
    struct Stack *next;
}SNode,*Link;
///初始化栈
Link Init(){
    Link p;
    p=new SNode;
    p=NULL;
    return p;
}
///入栈
Link Push(Link head,int x){
    Link p;
    p=new SNode;
    p->data=x;
    p->next=head;
    return p;
}
///出栈
Link Pop(Link head){
    Link p;
    p=head;
    if(p==NULL){
        cout<<"栈空了"<<endl;
    }
    else {
        p=p->next;
        free(head);
    }
    return p;
}
///取栈顶元素
int GetTop(Link head){
    if(head==NULL){
        cout<<"栈为空"<<endl;
        return -1;
    }
    else {
        return head->data;
    }
}
///判断栈空
int empty(Link head){
    if(head==NULL)
        return 1;
    else
        return 0;
}
///显示栈元素
void display(Link head){
    Link p;
    p=head;
    if(p==NULL){
        cout<<"栈为空"<<endl;
    }
    else {
        while(p!=NULL){
            cout<<p->data<<" ";
            p=p->next;
        }
    }
}
Link SetNull(Link head){
    Link p;
    p=head;
    while(p!=NULL){
        p=p->next;
        free(head);
        head=p;
    }
    return head;
}
int main()
{
    Link head;
    ///初始化栈
    head=Init();
    ///入栈
    int n;
    cin>>n;
    for(int i=0;i<n;i++){
        int x;
        cin>>x;
        head=Push(head,x);
    }

    ///出栈
    head=Pop(head);
    ///取栈顶元素
    int x=GetTop(head);
    cout<<"栈顶元素为: "<<x<<endl;
    ///判断栈空
    if(empty(head)==1){
        cout<<"栈为空"<<endl;
    }
    else {
        cout<<"栈不空"<<endl;
    }
    ///显示栈元素
    display(head);
    ///释放栈元素
    SetNull(head);
    return 0;
}
 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值