栈(Stack)是一种线性存储结构,它具有如下特点:
- 栈中的数据元素遵守”先进后出"(First In Last Out)的原则,简称FILO结构。
- 限定只能在栈顶进行插入和删除操作。
下面将使用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
",st->arr[st->top-1]);
st->top--;
}else{
return POP_ERROR;
}
return 0;
}
//求栈顶元素
int Top(struct stack *st){
printf("TOP VAL is %d
",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
",show(st1));
Top(st1);
pop(st1);
pop(st1);
printf("Count: %d
",show(st1));
return 0;
}