创建一个堆栈并用函数的嵌套调用该栈的全代码
时间: 2023-12-08 14:03:50 浏览: 24
下面是一个简单的堆栈实现,包括 push、pop、isEmpty 和 isFull 函数。使用函数的嵌套调用来操作堆栈。
```
#include <stdio.h>
#define MAXSIZE 10
int stack[MAXSIZE];
int top = -1;
void push(int value);
int pop();
int isEmpty();
int isFull();
int main() {
push(10);
push(20);
push(30);
printf("%d\n", pop());
printf("%d\n", pop());
printf("%d\n", pop());
printf("%d\n", pop()); // should print -1 (stack underflow)
return 0;
}
void push(int value) {
if (isFull()) {
printf("Stack overflow\n");
return;
}
top++;
stack[top] = value;
}
int pop() {
if (isEmpty()) {
printf("Stack underflow\n");
return -1;
}
int value = stack[top];
top--;
return value;
}
int isEmpty() {
return top == -1;
}
int isFull() {
return top == MAXSIZE-1;
}
```
在主函数中,我们使用 push 函数将三个元素压入堆栈中,然后使用 pop 函数弹出它们并打印它们的值。最后,我们尝试从一个空栈中弹出一个元素,这将导致堆栈下溢。整个过程使用函数的嵌套调用来操作堆栈。