栈(stack)是一种基本的线性数据结构,在栈上实现的是后进先出(LIFO)的策略。LIFO即最后入栈的元素最先出栈,入栈操作为push(),出栈操作为pop()。本文使用C语言+数组对栈进行实现。
1、栈的数组实现:
#include<stdio.h>
#include<stdbool.h>
#define MAXSIZE 100
typedef int datatype;
//定义栈s
struct stack
{
datatype data[MAXSIZE];
int top;
}s;
//栈初始化
void init(){
s.top = -1;
printf("初始化完毕。\n");
}
//判断栈是否为空
bool is_empty(){
if(s.top != -1)
return -1;
else
return 0;
}
//判断栈是否满
bool is_full(){
if(s.top != MAXSIZE-1)
return -1;
else
return 0;
}
//入栈操作,栈满时直接返回
datatype push(datatype da){
if(!is_full()){
printf("栈满\n");
}
else{
s.top++;
s.data[s.top] = da;
}
printf("入栈完毕。\n");
}
//出栈操作,栈为空时直接返回
datatype pop(){
if(!is_empty())
printf("栈为空\n");
else{
s.top--;
return s.data[s.top];
}
}
2、测试栈:
#include<stdio.h>
#include"my_stack.h"
void main(){
//初始化
init();
//入栈
for(int i=0; i<=8; i++){
push(i);
}
//出栈并打印结果
printf("%d\n", pop());
}
--------------------------------------------------------------------------------------------------------------------
上述实现方法由于在创建栈时已经定义好的固定的栈,并且仅可提供一个栈,显然不符合程序设计需要,现采用指针对栈的实现进行改进,使得可提供使用多个栈进行程序设计。
1、栈的实现:
#include<stdio.h>
#include<stdbool.h>
#define MAXSIZE 100
typedef int datatype;
struct stack
{
datatype data[MAXSIZE];
int top;
};
typedef struct stack Stack;
void init(Stack* s){
s->top = -1;
printf("初始化完毕。\n");
}
bool is_empty(Stack* s){
if(s->top != -1)
return -1;
else
return 0;
}
bool is_full(Stack* s){
if(s->top != MAXSIZE-1)
return -1;
else
return 0;
}
datatype push(Stack* s, datatype da){
if(!is_full(s)){
printf("栈满\n");
}
else{
s->top++;
s->data[s->top] = da;
}
printf("入栈完毕。\n");
}
datatype pop(Stack* s){
if(!is_empty(s))
printf("栈为空\n");
else{
s->top--;
return s->data[s->top];
}
}
2、栈测试:
#include<stdio.h>
#include"my_stack.h"
void main(){
Stack p, q;
Stack *s1, *s2;
s1 = &p;
s2 = &q;
//初始化
// init();
init(s1);
init(s2);
//入栈
for(int i=0; i<=8; i++){
push(s1, i);
}
for(int j=5; j<=15; j++){
push(s2, j);
}
//出栈并打印结果
printf("s1栈顶元素:%d\n", pop(s1));
printf("s2栈顶元素:%d\n", pop(s2));
}
持续更新中……