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

来源:互联网 发布:淘宝旺旺买家 编辑:程序博客网 时间:2024/05/18 07:38

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 0