您的位置:首页 > 理论基础 > 数据结构算法

数据结构-堆栈-数组实现

2017-10-04 14:46 274 查看

什么是堆栈?

堆栈形如数组,是一种数据存储方式.

堆栈存数像弹夹装弹



子弹从头开始装,最先装进去的,最后出来.

堆栈也是同样道理,最先装入的内容,最后出来,就是所谓的先进后出.

/*
* 堆 数组实现
*
* */

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

//定义堆栈
struct SNode {
int *data;
int top;
int maxSize;
};
typedef struct SNode * Stack;

//创建一个堆栈
Stack CreakStack(int maxSize){
Stack s=(Stack)malloc(sizeof(struct SNode));
s->data=(int *)malloc(maxSize * sizeof(int));
s->maxSize=maxSize;
s->top=-1;
return s;
}
//判断是否已满
bool isFull(Stack s){
return  (s->top==s->maxSize-1);
}
//判断是否为空
bool isEmpty(Stack s){
return  (s->top==-1);
}
//压栈
bool Push(Stack s,int num){
if(isFull(s)){
printf("堆栈满");
return false;
}
else{
s->data[++(s->top)]=num;
return true;
}
}
//出栈
int Pop(Stack s){
if(isEmpty(s)){
printf("堆栈空");
return NULL;
}
else{
return (s->data[(s->top)--]);
}
}

//测试
int main(){
Stack stack=CreakStack(10);
Pop(stack);
for(int i=0;i<10;i++){
Push(stack,i);
}
Push(stack,11);
for(int i=0;i<10;i++){
printf("%d  ",Pop(stack));
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: