数据结构 -- 栈的数组实现法

来源:互联网 发布:农村淘宝一单赚多少钱 编辑:程序博客网 时间:2024/06/04 01:09

栈(Stack)是一种线性存储结构,它具有如下特点:

  1. 栈中的数据元素遵守”先进后出"(First In Last Out)的原则,简称FILO结构。
  2. 限定只能在栈顶进行插入和删除操作。

下面将使用c++实现栈的结构与入栈出栈等操作:

参考代码:

#include <cstdio>#include <iostream>#include <cstdlib>using namespace std;#define MAXN 100#define PUSH_ERROR 0x1#define POP_ERROR 0x2struct stack{int arr[MAXN];int top;};//初始化栈结构void init_stack(struct stack *st){st->top = 0;return;}//入栈int push(struct stack *st , int val){if (st->top < MAXN){st->arr[st->top++] = val;}else{return PUSH_ERROR;}return 0;}//出栈int pop(struct stack *st){if (st->top > 0){printf("The POP val is %d\n",st->arr[st->top-1]);st->top--;}else{return POP_ERROR;}return 0;}//求栈顶元素int Top(struct stack *st){printf("TOP VAL is %d\n",st->arr[st->top-1]);return 0;}//求栈的大小int show(struct stack *st){int count = 0;for (int i = 0 ; i < st->top ; i++){count++;}return count;}int main(void){struct stack *st1 = (struct stack *)malloc(sizeof(struct stack));init_stack(st1);push(st1,1);push(st1,3);push(st1,2);printf("Count: %d \n",show(st1));Top(st1);pop(st1);pop(st1);printf("Count: %d \n",show(st1));return 0;}


原创粉丝点击