棧(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));
}
持續更新中……