一、栈
一、什么是栈?
栈(Stack) 是一种只能在一端进行插入和删除操作的线性数据结构。这一端被称为栈顶(Top) ,另一端固定不动,称为栈底(Bottom)。

这里大家把它认为是一个水桶就行,记住一个特点:后进先出
二、栈的基本操作
操作 | 作用 |
---|---|
push() |
将一个元素压入栈顶 |
pop() |
将栈顶元素弹出并返回 |
peek() 或 top() |
查看栈顶元素但不移除它 |
isEmpty() |
判断栈是否为空 |
isFull() |
判断栈是否已满(适用于数组实现) |
size() |
返回栈中元素的数量 |
三、栈的实现方式
- 使用数组实现(静态栈)
定义结构体,顺序表这部分都懂
cs
#define MAX_SIZE 100 // 最大容量
typedef struct {
int arr[MAX_SIZE]; // 存储栈的数组
int top; // 栈顶指针(初始为 -1)
} Stack;
初始化栈
cs
void initStack(Stack *s) {
s->top = -1;//因为数组默认下标是0,空栈的下标设置为-1
}

压栈 push
cs
void push(Stack *s, int value) {
if (!isFull(s)) {
s->arr[++(s->top)] = value;//栈顶指针向上移动
} else {
printf("Stack overflow\n");
}
}

弹栈 pop
cs
int pop(Stack *s) {
if (!isEmpty(s)) {
return s->arr[(s->top)--];//根压栈相反,取出来那栈顶指针就下移
} else {
printf("Stack underflow\n");
return -1;
}
}
查看栈顶 peek
cs
int peek(Stack *s) {
if (!isEmpty(s)) {
return s->arr[s->top];
} else {
printf("Stack is empty\n");
return -1;
}
}
2. 使用链表实现(动态栈)
把它当成单链表就行,只不过多了个指向最后一个节点的top指针
代码演示一下吧 :
定义节点结构
cs
typedef struct Node {
int data;
struct Node* next;
} Node;
定义栈结构
cs
typedef struct {
Node* top; // 栈顶指针
} Stack;
初始化栈
cs
void initStack(Stack *s) {
s->top = NULL;
}
判断栈空
cs
int isEmpty(Stack *s) {
return s->top == NULL;
}
压栈 push
cs
void push(Stack *s, int value) {
Node* newNode = (Node*)malloc(sizeof(Node));
if (newNode == NULL) {
printf("Memory allocation failed\n");
return;
}
newNode->data = value;
newNode->next = s->top;
s->top = newNode;
}
弹栈 pop
cs
int pop(Stack *s) {
if (!isEmpty(s)) {
Node* temp = s->top;
int value = temp->data;
s->top = s->top->next;
free(temp);
return value;
} else {
printf("Stack underflow\n");
return -1;
}
}
查看栈顶 peek
cs
int peek(Stack *s) {
if (!isEmpty(s)) {
return s->top->data;
} else {
printf("Stack is empty\n");
return -1;
}
}
下期明天更,睡觉了宝子们!