顺序栈的实现

        定义顺序栈的存储结构,并且实现基本的操作。包括构造空的顺序栈,建立包含若干的元素的顺序栈,入栈,出栈,输出顺序栈,求出栈长度,判断是否为空,判断是否为满等。

list.h

#include<string.h>
#include<ctype.h>
#include<malloc.h>
#include<limits.h>
#include<stdio.h>
#include<stdlib.h>
// #include<io.h>
#include<math.h>
// #include<process.h>
// 函数状态的代码
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
// status是函数的返回值类型,该值是函数结果状态代码,譬如ok等
typedef int Status;

sqstack.h

#include"list.h"

#define MaxSize 5
#define Increment 2
typedef int ElemType;
typedef struct {
  ElemType data[MaxSize];
  // 栈顶指针
  int top;
} SeqStack;

//创建顺序栈 
SeqStack* createStack() {
  SeqStack *t = (SeqStack *)malloc(sizeof(SeqStack));
  // 一开始栈顶指针指向-1
  t->top = -1;
  return t;
}

//判断栈是否为空
int empty(SeqStack *s) {
  return s->top == -1;
}

//判断栈是否满
int full(SeqStack *s) {
	// 从0开始
  return s->top == MaxSize - 1;
}

//元素x进栈 
void push(SeqStack *s, ElemType x) {
  // 判断是否栈满
  if (full(s))exit(1);
  // 栈顶指针先+1再入栈
  s->data[++s->top] = x;
}

//出栈 
void pop(SeqStack *s, ElemType &e) {
	// 判断是否栈空
  if (empty(s)) exit(1);
  // 先出栈再-1
  e = s->data[s->top--];
}

//取栈顶元素的值
ElemType GetTop(SeqStack *s) {
  if (empty(s)) exit(1);
  return s->data[s->top];
}

//求栈的元素个数 
int GetLength(SeqStack* s) {
  return s->top + 1; 
}
teststack.cpp
#include "sqstack.h"

int main() {
  SeqStack *s = createStack();
  
  ElemType e;
  printf("请输入要入栈的元素个数:\n");
  int n;
  int i = 0;
  scanf("%d",&n);
  printf("请输入要入栈的元素:\n");
  while(!full(s)&&(i < n)){
    scanf("%d",&e);
    push(s,e);
    i++;
}

  printf("逐个出栈:\n");
  while(!empty(s)){
    pop(s,e);
    printf("%d  ",e);
}

  printf("\n");
  push(s, 70);
  printf("栈有%d个元素,栈顶元素为:%d\n", GetLength(s), GetTop(s));
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值