数据结构之堆栈

1.线性表实现堆栈

#include <stdio.h>
#include <stdlib.h>

#define maxsize 100

typedef enum{true,false
}bool;
typedef struct SNode * Stack;
typedef int ElementType;

//定义堆栈结构
struct SNode{
  ElementType data[maxsize];
  int top;
};


//生成空堆栈
Stack createStack(){
  Stack stack=(Stack)malloc(sizeof(struct SNode));
  stack->top=0;
}

// 判断堆栈是否已满
bool isFull(Stack s){
  if(s->top==maxsize){
    return true;
  }
  return false;
}

//入栈
bool push(Stack s,ElementType e){
  if(s->top==maxsize){
    printf("栈满\n");
    return false;
  }
  else{
    s->data[s->top]=e;
    s->top++;
    return true;
  }
}

//出栈
ElementType pop(Stack s){
  if(s->top==0){
    printf("栈空\n");
    return ;
  }
  ElementType e=s->data[s->top-1];
  s->top--;
  return e;
}

//判断是否为空
bool isEmpty(Stack s){
  if(s->top==0){
  return true;
  }
  return false;
}

int main(int argc, char *argv[]) {
  Stack stack=createStack();
  if(isEmpty(stack)==true){
  printf("空栈\n");
  }
  push(stack,1);
  push(stack,2);
  push(stack,3);
  push(stack,4);
  push(stack,5);
  if(isEmpty(stack)==false){
    printf("不是空栈\n");
  }
  int length=stack->top;
  for(int i=0;i<length;i++){
    printf("%d\t",pop(stack));
  }
  if(isEmpty(stack)==true){
    printf("空栈\n");
  }
  return 0;
}

猜你喜欢

转载自www.cnblogs.com/hsiaolung/p/9259989.html