复习(数据结构):栈:c语言:数组

1. 数据结构

 typedef struct{
     SElemType data[MAXSIZE];
     int top;  //头部栈指针
 }SqStack;

2. 操作

  • 栈顶:S.top;初始设置S.top=-1; 栈顶元素S.data[S.top];
  • 进栈: 栈不满,栈顶先+1,再送值到栈顶元素
  • 出栈:栈非空,先取栈顶元素,再栈顶的指针-1
  • 栈空:S.top==-1;栈满条件:S.top==MaxSize-1;栈长:S.top+1


 //--------------------

#include "stdio.h"
#include "stdlib.h"
#include "math.h"
#include"time.h"

#define OK 1
#define ERROR 1
#define TRUE 1
#define FALSE 0
#define MAXSIZE 20  //分配存储空间

 typedef int Status;
 typedef int SElemType;

 //顺序栈

 typedef struct{
     SElemType data[MAXSIZE];
     int top;  //头部栈指针
 }SqStack;

 Status visit(SElemType c){
     printf("%d ", c);
     return OK;
 }
 //----------------------------------

//空栈

 Status InitStack(SqStack *s){
     s->top=-1;
     return OK;
 }
 Status StackEmpty(SqStack s){
     if(s.top==-1)
         return TRUE;
     else
         return FALSE;
 }

 Status ClearStack(SqStack *s){
     s->top=-1;
     return OK;
 }
 Status StackLength(SqStack s){
     return s.top+1;
 }

 Status GetTop(SqStack s,SElemType * e){
     if(s.top==-1)
         return FALSE;
     else
         *e=s.data[s.top];
     return OK;
 }
 Status Push(SqStack *s,SElemType e){
     if(s->top==MAXSIZE-1)
         return ERROR;
     s->top++;
     s->data[s->top]=e;
     return OK;
 }

 Status Pop(SqStack *s,SElemType *e){
     if(s->top==-1)
         return ERROR;
     *e=s->data[s->top];
     s->top--;
     return OK;
 }
 Status StackTraverse(SqStack s){
     int i=0;
     while(i<=s.top){
         visit(s.data[i++]);
     }
     printf("\n");
     return OK;
 }

 int main()
 {
     int j,e;
     SqStack s;
     if(InitStack(&s)==OK)
         for(j=1;j<=10;j++)
             Push(&s,j);
     printf("栈中的元素依次是: ");
     StackTraverse(s);
     Pop(&s,&e);
     printf("弹出的栈顶元素 e=%d\n",e);
     ClearStack(&s);
     return 0;

 }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值