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

栈(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 0x2


struct 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;
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值