栈的基本操作pra
时间: 2023-07-06 17:18:06 浏览: 50
栈是一种数据结构,它的基本操作包括以下几个:
1. push:将一个元素压入栈顶;
2. pop:将栈顶的元素弹出;
3. top:获取栈顶元素,但不弹出;
4. isEmpty:判断栈是否为空;
5. isFull:判断栈是否已满(只适用于静态栈)。
在实现栈的时候,通常有两种方式:使用数组或使用链表。使用数组实现的栈称为静态栈,而使用链表实现的栈称为动态栈。静态栈的大小是固定的,而动态栈的大小可以根据需要进行扩展。
以下是一个使用数组实现的静态栈的示例代码:
```
#include <stdio.h>
#define MAX_SIZE 10
int stack[MAX_SIZE];
int top = -1;
void push(int x) {
if (top == MAX_SIZE - 1) {
printf("Error: stack is full\n");
return;
}
top++;
stack[top] = x;
}
void pop() {
if (top == -1) {
printf("Error: stack is empty\n");
return;
}
top--;
}
int topElement() {
if (top == -1) {
printf("Error: stack is empty\n");
return -1;
}
return stack[top];
}
int isEmpty() {
return top == -1;
}
int isFull() {
return top == MAX_SIZE - 1;
}
int main() {
push(1);
push(2);
push(3);
printf("%d\n", topElement()); // 输出3
pop();
printf("%d\n", topElement()); // 输出2
return 0;
}
```