在栈上执行的基本操作如下:
Push:向栈顶添加一个元素
Pop:从栈顶移除一个元素
IsEmpty:检查栈是否为空
IsFull:检查栈是否满
Peek:获取顶部元素的值而不删除它
实现思路:
- 使用称为 TOP 的指针用于跟踪堆栈中的顶部元素。
- 在初始化栈的时候,我们将TOP的值设置为-1,这样我们就可以通过比较TOP == -1来判断栈是否为空。
- 在push一个元素时,我们增加 TOP 的值并将新元素放置在 TOP 指向的位置。(在push之前,检查堆栈是否已经满了)
- 在pop一个元素时,我们返回 TOP 指向的元素并减少它的值。(在pop之前,检查堆栈是否已经为空)
// Stack implementation in C
#include <stdio.h>
#include <stdlib.h>
#define MAX 10
struct stack {
int items[MAX];
int top;
int count;
};
typedef struct stack st;
void createStack(st *s) {
s->top = -1;
s->count = 0;
}
int isFull(st *s) {
if (s->top == MAX - 1) {
return 1;
} else {
return 0;
}
}
int isEmpty(st *s) {
if (s->top == -1) {
return 1;
} else {
return 0;
}
}
void push(st *s, int item) {
if (isFull(s)) {
printf("STACK FULL\n");
} else {
s->top++;
s->items[s->top] = item;
s->count++;
}
}
int pop(st *s) {
if (isEmpty(s)) {
printf("STACK EMPTY\n");
} else {
int popped = s->items[s->top];
s->top--;
s->count--;
return popped;
}
}
void printStack(st *s) {
for (int i = 0; i < s->count; i++) {
printf("%d\n", s->items[i]);
}
}
// Driver code
int main() {
st *s = (st *)malloc(sizeof(st));
createStack(s);
push(s, 1);
push(s, 2);
push(s, 3);
push(s, 4);
printf("Current Stack:\n");
printStack(s);
printf("\n");
printf("%d is popped out.\n", pop(s));
printf("Current Stack:\n");
printStack(s);
printf("\n");
printf("%d is popped out.\n", pop(s));
printf("Current Stack:\n");
printStack(s);
printf("\n");
push(s, 5);
printf("\nAfter pushing 5 into the stack\n");
printf("Current Stack:\n");
printStack(s);
printf("\n");
}