显示栈里面的数据 C语言
时间: 2024-05-11 08:17:28 浏览: 7
要显示栈里面的数据,可以通过以下步骤:
1. 定义一个指针变量,指向栈顶元素。
2. 通过循环遍历栈中的每个元素,输出其值,直到栈底。
3. 每次遍历需要将指针变量指向下一个元素。
以下是示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
int stack[MAX_SIZE];
int top = -1;
void push(int data) {
if (top >= MAX_SIZE - 1) {
printf("Stack Overflow\n");
return;
}
stack[++top] = data;
}
int pop() {
if (top == -1) {
printf("Stack Underflow\n");
return -1;
}
return stack[top--];
}
void display() {
if (top == -1) {
printf("Stack is empty\n");
return;
}
int *ptr = &stack[top];
printf("Stack:\n");
while (ptr >= &stack[0]) {
printf("%d\n", *ptr--);
}
}
int main() {
push(10);
push(20);
push(30);
display();
pop();
display();
return 0;
}
```
输出结果:
```
Stack:
30
20
10
Stack:
20
10
```