链栈的运算 置空/判空/进栈/出栈/读栈顶

#include<iostream>
#include<stdlib.h>
#include<stdio.h>
#define MAXSIZE 100
using namespace std;
//链栈的本质上是单链表,无非是限制了插入和删除运算只能在链头进行。
//由于在链头运算,不用像单链表那样附加头结点,更方便运算。
//链栈的类型
struct node{
    int data ;
    struct node *next ;

};
//由于没有对头结点指针,进行函数传递,导致代码看起来很弱,
//传入的头指针地址,返回的也是头指针地址

//链栈置空
struct node* setnull(struct node *top){

  top = NULL ;
  return top ;
}

//判链空
int isempty(struct node *top){
    if(top == NULL)
        return 1;
    return 0 ;
}

//进栈
struct node * push(struct node *top ,  int x){
    struct node *s = (struct node *)malloc(sizeof(struct node)) ;
    s->data = x ;
    s->next = top ;
    top = s ;
    cout<<"push () top = " << top << endl;
    return top ;
}

//出栈
struct node *  pop(struct node *top){
    if(top == NULL)
        return NULL ; //栈为空时,返回NULL
    struct node *s = top ;
    top= top->next ;
    free(s) ;
    return top;
}

//读栈顶元素
int gettop(struct node *top){
    if(top == NULL)
        return NULL ;  // 栈为空时,返回NULL
    return top->data ;
}
int main(){
    struct node *s ;

    s=setnull(s) ;
    cout << "s = " << s<<endl;
    for(int i =1  ;i <10 ; i++)
        {
            s  = push(s , i) ;
        cout<< "s = "<<s << endl;
        }
    while(!isempty(s)){
        cout<<"出栈顺序: "<<gettop(s)<<endl ;
        s = pop(s ) ;
    }
   return 0 ;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值