一起创业网-为互联网创业者服务

程序怎么实现堆栈

堆栈(Stack)是一种后进先出(LIFO)的数据结构,可以通过不同的方式实现。以下是几种常见的堆栈实现方法:

静态数组实现

特点:使用固定大小的数组,长度在编译时确定。

优点:实现简单,不容易出错。

缺点:不够灵活,长度固定。

示例代码

```c

include

define MAX_SIZE 100

int stack[MAX_SIZE];

int top = -1;

void push(int value) {

if (top >= MAX_SIZE - 1) {

printf("Stack is full\n");

return;

}

stack[++top] = value;

}

int pop() {

if (isEmpty()) {

printf("Stack is empty\n");

return -1;

}

return stack[top--];

}

int isEmpty() {

return top == -1;

}

int isFull() {

return top >= MAX_SIZE - 1;

}

int main() {

int value;

int choice;

do {

printf("To push data into the stack, please enter 1; to pop data from the stack, enter 0; to stop the operation, enter -1.\r\n");

scanf("%d", &choice);

if (choice == 1) {

printf("Enter value to push: ");

scanf("%d", &value);

push(value);

} else if (choice == 0) {

printf("Popped value: %d\n", pop());

}

} while (choice != -1);

return 0;

}

```

动态数组实现

特点:长度可以在运行时确定,并且可以动态调整。

优点:灵活。

缺点:实现复杂度较高。

示例代码

```c

include

include

typedef struct {

int *array;

size_t size;

size_t capacity;

} Stack;

Stack* createStack(size_t initialCapacity) {

Stack *stack = malloc(sizeof(Stack));

if (stack == NULL) {

return NULL;

}

stack->array = malloc(initialCapacity * sizeof(int));

if (stack->array == NULL) {

free(stack);

return NULL;

}

stack->size = 0;

stack->capacity = initialCapacity;

return stack;

}

void destroyStack(Stack stack) {

if (*stack != NULL) {

free((*stack)->array);

free(*stack);

*stack = NULL;

}

}

void push(Stack *stack, int value) {

if (stack->size == stack->capacity) {

stack->capacity *= 2;

stack->array = realloc(stack->array, stack->capacity * sizeof(int));

if (stack->array == NULL) {

printf("Memory allocation failed\n");

return;

}

}

stack->array[stack->size++] = value;

}

int pop(Stack *stack) {

if (isEmpty(stack)) {

printf("Stack is empty\n");

return -1;

}

return stack->array[--stack->size];

}

int isEmpty(Stack *stack) {

return stack->size == 0;

}

int main() {

Stack *stack = createStack(2);

push(stack, 1);

push(stack, 2);

push(stack, 3);

printf("Popped value: %d\n", pop(stack));

destroyStack(&stack);

return 0;

}

```

链式结构实现

特点:无长度限制,动态分配内存。

优点:灵活,动态大小。

缺点:实现相对复杂。

示例代码