栈的基本操作

本文详细介绍了栈的基本概念、顺序栈的实现方法,并通过代码示例展示了如何使用栈进行数据存储与操作。同时,文章指出掌握链表知识后,栈和队列的实现将更加轻松。

 栈的基本操作

栈的基本操作

“a.h”

#include
#include
#include
#include

#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0

typedef int ElemType;
typedef int Status;

#define INIT_SIZE 10
#define STACKINCREMENT 2
typedef struct SqStack{
    ElemType *top;
 ElemType *base;
 int stacksize;
}SqStack;  
 //顺序栈,先分配一定的储存空间。

"b.h"

#include"a.h"

Status InitStack(SqStack *s);

Status DestroyStack(SqStack *s);

Status ClearStack(SqStack *s);

Status StackEmpty(SqStack s);

Status StackLength(SqStack s);

Status GetTop(SqStack s,ElemType *e);

Status Push(SqStack *s ,ElemType e);  //进栈

Status Pop(SqStack *s,ElemType *e);  //出栈

Status StackTraverse(SqStack s,Status(*fun)(ElemType));

 

 

"b.c"

#include"b.h"

Status InitStack(SqStack *s)  
{
      (*s).base=(ElemType*)malloc(INIT_SIZE*sizeof(ElemType));
       if(!(*s).base)
     return ERROR;
    (*s).top=(*s).base;
    (*s).stacksize=INIT_SIZE;
    return TRUE;
}

Status DestroyStack(SqStack *s)
{
       free((*s).base);
    (*s).base=(*s).top=NULL;
    (*s).stacksize=0;
    return TRUE;
}

Status ClearStack(SqStack *s)
{
       (*s).top=(*s).base;
    return TRUE;
}

Status StackEmpty(SqStack s)
{
       if(s.base==s.top)
     return TRUE;
    else
     return FALSE;
}

Status StackLength(SqStack s)
{
        return s.top-s.base;
}

Status GetTop(SqStack s,ElemType *e)
{
 if(s.top>s.base){
        (*e)=*(s.top-1);
     return TRUE;
 }
 else
  return ERROR;
}

Status Push(SqStack *s ,ElemType e)  //进栈
{
 if((*s).top-(*s).base>=(*s).stacksize){
     (*s).base=(ElemType*)realloc((*s).base,(INIT_SIZE+STACKINCREMENT)*sizeof(ElemType));
         if(!(*s).base)
    return ERROR;
   
   (*s).top=(*s).base+(*s).stacksize;
   (*s).stacksize+=STACKINCREMENT;
 }
       *((*s).top)=e;
    (*s).top++;
    return OK;
}
Status Pop(SqStack *s,ElemType *e)  //出栈
{
 if(!StackEmpty(*s)){
    *e=*(--(*s).top);
    return OK;
 }
   else
    return ERROR;
}

Status StackTraverse(SqStack s,Status(*fun)(ElemType))
{
   ElemType *p=s.top;
      if(!StackEmpty(s)){
    printf("栈定");
    while(p!=s.base)
        fun(*(--p));
    printf("栈底\n");
    return OK;
   }
   else
    return ERROR;
}

 

 

"main.c"

#include"b.h"
#define LEN 5

Status fun(ElemType e)

    printf(" %d ",e);
 return TRUE;
}

int main()
{
 int i;
    SqStack s;
 ElemType e;
 InitStack(&s);
 if(StackEmpty(s))
  printf("该栈为空!!!\n");
 for(i=0;i
   printf("请输入元素,进栈: ");
   scanf("%d",&e);
   Push(&s,e);
 }
 StackTraverse(s,fun);
 printf("该栈的长度为 :%d \n",StackLength(s));

 for(i=0;i<3;i++){
   Pop(&s,&e);
   printf("出栈的元素为: %d\n",e);
 }
 StackTraverse(s,fun);
 printf("该栈的长度为 :%d \n",StackLength(s));

 

 

链表学好之后,栈和队列就好写多了。

下面队列的干活

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值