C++ 输出stack内容
时间: 2023-03-28 11:04:44 浏览: 131
可以使用以下代码输出stack内容:
```c
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define STACK_SIZE 10
typedef struct {
int data[STACK_SIZE];
int top;
} Stack;
void initStack(Stack *s) {
s->top = -1;
}
bool isStackEmpty(Stack *s) {
return s->top == -1;
}
bool isStackFull(Stack *s) {
return s->top == STACK_SIZE - 1;
}
void push(Stack *s, int value) {
if (isStackFull(s)) {
printf("Stack is full!\n");
exit(1);
}
s->top++;
s->data[s->top] = value;
}
int pop(Stack *s) {
if (isStackEmpty(s)) {
printf("Stack is empty!\n");
exit(1);
}
int value = s->data[s->top];
s->top--;
return value;
}
void printStack(Stack *s) {
printf("Stack contents: ");
for (int i = s->top; i >= ; i--) {
printf("%d ", s->data[i]);
}
printf("\n");
}
int main() {
Stack s;
initStack(&s);
push(&s, 1);
push(&s, 2);
push(&s, 3);
printStack(&s);
pop(&s);
printStack(&s);
return ;
}
```
输出结果为:
```
Stack contents: 3 2 1
Stack contents: 2 1
```