面试题答案
一键面试#include <stdio.h>
#include <stdlib.h>
// 定义栈的结构体
typedef struct Stack {
int *data;
int top;
int capacity;
} Stack;
// 创建一个新的栈
Stack* create_stack(int size) {
Stack *stack = (Stack*)malloc(sizeof(Stack));
stack->data = (int*)malloc(size * sizeof(int));
stack->top = -1;
stack->capacity = size;
return stack;
}
// 判断栈是否为空
int is_empty(Stack *stack) {
return stack->top == -1;
}
// 入栈操作
void push(Stack *stack, int value) {
if (stack->top == stack->capacity - 1) {
printf("Stack overflow\n");
return;
}
stack->data[++stack->top] = value;
}
// 出栈操作
int pop(Stack *stack) {
if (is_empty(stack)) {
printf("Stack underflow\n");
exit(EXIT_FAILURE);
}
return stack->data[stack->top--];
}
// 获取栈顶元素
int peek(Stack *stack) {
if (is_empty(stack)) {
printf("Stack is empty\n");
exit(EXIT_FAILURE);
}
return stack->data[stack->top];
}
// 释放栈的内存
void free_stack(Stack *stack) {
free(stack->data);
free(stack);
}
你可以使用以下方式调用这些函数:
int main() {
Stack *stack = create_stack(5);
push(stack, 10);
push(stack, 20);
push(stack, 30);
printf("Is stack empty? %s\n", is_empty(stack)? "Yes" : "No");
printf("Top element: %d\n", peek(stack));
printf("Popped element: %d\n", pop(stack));
printf("Is stack empty? %s\n", is_empty(stack)? "Yes" : "No");
free_stack(stack);
return 0;
}