栈是数据结构中相对而言比较简单的结构容器,它的特点是后进先出。与队列不同,栈的出口只有一个,你可以理解为像桶一样的容器,如下图所示:
我个人认为,一个栈的组成是:初始化顶端指针,入栈,出栈,查看顶端元素,判断栈是否为空,判断栈是否已满
我写了一串代码,可以说基本呈现了栈的基本原理:
#include<stdio.h>
#include<stdlib.h>
#define max 100
typedef struct {
int data[max];
int top;//栈的顶端指针
} stack;
int isempty(stack *head);//检查栈是否为空
int isfull(stack *head);//检查栈是否已满
void initialize(stack *head);//初始化栈的顶端指针
void into(stack *head, int value); //入栈
void out(stack *head);//出栈
void see(stack *head);//查看顶端元素
int main() {
stack head;
initialize(&head);
into(&head, 10);
into(&head, 20);
into(&head, 30);
see(&head);
system("pause");
out(&head);
out(&head);
see(&head);
return 0;
}
void initialize(stack *head) {
head->top = -1;
}
int isempty(stack *head) {
if (head->top == 0) {
printf("栈为空!\n");
return -1;
} else {
return 1;
}
}
int isfull(stack *head) {
if (head->top == max) {
printf("栈已经满了!\n");
return -1;
} else {
return 1;
}
}
void into(stack *head, int value) {
if (!isfull(head)) {
printf("栈已经满了,无法再继续添加元素了!\n");
return;
} else {
int num;
head->top++;
head->data[head->top] = value;
num = head->data[head->top];
printf("元素%d已经入栈了!\n");
}
}
void out(stack *head) {
if (!isempty(head)) {
printf("栈是空的。无法再继续删除元素了!\n");
return;
} else {
int num;
num = head->data[head->top];
printf("被移除的元素是:%d\n", num);
head->data[head->top] = 0;
head->top--;
}
}
void see(stack *head) {
int num;
num = head->data[head->top];
printf("目前的顶端元素是:%d\n", num);
}
如果没有意外,那么这将是这串代码的运行结果:
由此可见,栈的原理很简单,不是特别难,你说对吧?