C/C++面试试题专栏:用C语言实现栈(三)

栈有什么特点呢?

栈中的元素先进后出。常见的栈的操作有出栈、压栈、删除等。

在压栈时,需要检查栈是否已满;

在出栈时,需要检查栈是否已空。

用数组模拟栈的实现如下:

#define _STACKSIZE 100

//栈的声明
struct stack{
    int stk[_STACKSIZE];
    int top;
}

//栈的初始化
void ini_stack(struct stack *s){
    memset(s->stk,0,sizeof(s->stk));//用menset把栈初始化为0
    s->top=-1;
}

//压栈
int push(struct stack *s,int data){
    //判断栈是否满
    if(s->data==_STACKSIZE-1){
       printf("the stack is full.\n");
       return 1;
    }
    ++(s->top);
    s->stk[s->top]=data;
    return 0;
}

//出栈
int pop(struct stack *s){
    int temp;
    //判断是否为空
    if(s->data<0){
        printf("the stack is empty.\n")
        return -1;
    }
    temp=s->stk[s->top];
    --(s->top);
    return temp;
}

亦可以用链表实现栈,后续补上。

//栈的声明
struct stack{
ElementType data;
struct stack *next;
}

//压栈
int push(struct stack *s,ElementType edata){
   //链表栈如需判满
   struct stack *newstack = new stack;
   newstack->data=edata;
   newstack->next=s->next;
   s->next=newstack;
   return 1;
}

//出栈
//s 为栈顶指针
int pop(struct stack *s){
   //判空
   if(s->next==NULL)
      return 0;
   struct stack *sTemp;
   //当前栈顶指针赋值非sTemp,他们指向同一块内存区域
   sTemp=s;
   //栈顶指针指向上一个元素
   s=sTemp->next;
   //清除栈顶指针指向的内存区域
   free(sTemp);
   return 1;
}
  

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值