下面来介绍栈的两种实现方式:
一、数组
cpp
#include<stdio.h>
#include<stdlib.h>
#define E int
#define MAX_STACK 5
//数据结构-栈(数组实现)
typedef struct my_stack {
E *sta;//栈大小为5
int pos;//栈顶位置
}my_stack;
//初始化栈
void initialise(my_stack* stack) {
stack->sta = (E*)malloc(MAX_STACK * sizeof(E));
if (stack->sta == NULL) return;
stack->pos = -1;
}
//没满就返回假
int is_full(my_stack* stack) {
return (stack->pos == MAX_STACK-1);
}
//进栈
int push_stack(my_stack* stack, E ele) {
if (is_full(stack))return 0;
stack->sta[++stack->pos] = ele;
return 1;
}
//出栈
E poll_stack(my_stack* stack) {
if (stack->pos < 0)return 0;
return stack->sta[stack->pos--];
}
int main() {
my_stack stack;
initialise(&stack);
for (int i = 1; i <= 5; i++) {
push_stack(&stack, 20*i);
}
for (int i = 0; i < 5; i++) {
printf("%d\n", poll_stack(&stack));
}
return 0;
}
二、单链表
相对于数组实现来说,单链表实现会稍微复杂点
注:头文件和宏定义与上面一样
cpp
typedef struct my_list {
E element;
struct my_stact* next;
}List;
typedef struct my_stact {
List* list;
int size;
}my_stact;
//初始化
void initialise(my_stact* stack) {
stack->list = NULL;
stack->size = 0;
}
int is_full(my_stact* stack) {
return (stack->size == MAX_STACK);
}
int push_stack(my_stact* stack, E ele) {
if (is_full(stack)) return 0;
List* tem = stack->list;
int flag = 0;
for (int i = 0; i < stack->size; i++) {
if (i >= 1)
tem = tem->next;
flag++;
}
List* ptr = (List*)malloc(sizeof(List));//开辟空间
if (ptr== NULL)return 0;//为空开辟失败
ptr->next = NULL;//将新开辟的节点的下一节点指针置为空
ptr->element = ele;
if (flag == 0) {
stack->list = ptr;
stack->size++;
return 1;
}//首次开辟节点情况
tem->next = ptr;//非第一个元素情况
stack->size++;
return 1;
}
E poll_stack(my_stact* stack) {
if (stack->size == 0)return 0;
List* tem = stack->list;
for (int i = 0; i < stack->size; i++) {
if(i>=1)
tem = tem->next;//移动节点
}
E e = tem->element;
stack->size--;
free(tem);
tem = NULL;
return e;
}
int main() {
my_stact stact;
initialise(&stact);
for (int i = 1; i <= 5; i++) {
push_stack(&stact, 20*i);
}
for (int i = 0; i < 5; i++) {
printf("%d\n", poll_stack(&stact));
}
return 0;
}