用c++,建立一个栈,实现压栈、取栈顶元素、出栈操作
时间: 2024-05-05 15:15:38 浏览: 12
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
typedef struct {
int data[MAX_SIZE];
int top;
} Stack;
void initStack(Stack *s) {
s->top = -1;
}
int isFull(Stack *s) {
return s->top == MAX_SIZE - 1;
}
int isEmpty(Stack *s) {
return s->top == -1;
}
void push(Stack *s, int value) {
if (isFull(s)) {
printf("Stack is full.\n");
return;
}
s->top++;
s->data[s->top] = value;
}
int top(Stack *s) {
if (isEmpty(s)) {
printf("Stack is empty.\n");
return -1;
}
return s->data[s->top];
}
int pop(Stack *s) {
if (isEmpty(s)) {
printf("Stack is empty.\n");
return -1;
}
int value = s->data[s->top];
s->top--;
return value;
}
int main() {
Stack s;
initStack(&s);
push(&s, 1);
push(&s, 2);
push(&s, 3);
printf("Top element: %d\n", top(&s));
printf("Pop element: %d\n", pop(&s));
printf("Pop element: %d\n", pop(&s));
printf("Pop element: %d\n", pop(&s));
printf("Pop element: %d\n", pop(&s));
return 0;
}
```