不同类型的栈声明之间的区别取决于栈的实现方式和功能特点。下面是几种常见的栈类型和它们的区别,以及相应的代码示例:
静态栈(Static Stack):
#define MAX_SIZE 100
int stack[MAX_SIZE];
int top = -1;
void push(int value) {
if (top == MAX_SIZE - 1) {
printf("Stack Overflow\n");
return;
}
stack[++top] = value;
}
int pop() {
if (top == -1) {
printf("Stack Underflow\n");
return -1;
}
return stack[top--];
}
动态栈(Dynamic Stack):
struct Node {
int data;
struct Node* next;
};
struct Node* top = NULL;
void push(int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode->next = top;
top = newNode;
}
int pop() {
if (top == NULL) {
printf("Stack Underflow\n");
return -1;
}
struct Node* temp = top;
int value = temp->data;
top = top->next;
free(temp);
return value;
}
堆栈(Heap Stack):
#include
struct Stack {
int* data;
int top;
};
struct Stack* createStack(int size) {
struct Stack* stack = (struct Stack*)malloc(sizeof(struct Stack));
stack->data = (int*)malloc(size * sizeof(int));
stack->top = -1;
return stack;
}
void push(struct Stack* stack, int value) {
stack->data[++stack->top] = value;
}
int pop(struct Stack* stack) {
return stack->data[stack->top--];
}
上述示例展示了不同类型的栈声明和基本操作的实现方法。使用这些示例代码,可以根据需求选择合适的栈类型并进行相应的操作。