前言
链式栈的基本操作——创建销毁增删查
一、头文件
#ifndef LINKED_STACK_H
#define LINKED_STACK_H
#define _CRT_SECURE_NO_WARNINGS
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
typedef int ElementType;
//栈的结点栈帧
typedef struct node {
ElementType data;
struct node *next;
}StackFrame;
typedef struct {
StackFrame* top;
}LinkedStack;
//创建链式栈
LinkedStack* stack_create();
//入栈
void stack_push(StackFrame** top, ElementType data);
//出栈
ElementType stack_pop(LinkedStack* stack);
//判空
bool is_empty(LinkedStack* stack);
//访问栈顶元素
ElementType stack_peek(LinkedStack *stack);
// 销毁链式栈
void stack_destroy(LinkedStack* stack);
#endif //!LINKED_STACK_H
二、栈的基本操作
#include "stack.h"
//创建链式栈
LinkedStack* stack_create() {
return calloc(1, sizeof(LinkedStack));
}
//判空
bool is_empty(LinkedStack* stack) {
return stack->top == NULL;
}
//入栈
void stack_push(LinkedStack* stack, ElementType data) {
StackFrame* new_frame = malloc(sizeof(StackFrame));
if (new_frame == NULL) {
printf("error:new_frame failed in stack_push.\n");
exit(1);
}
//初始化新栈帧
new_frame->data = data;
new_frame->next = stack->top;
//更新栈顶指针
stack->top = new_frame;
}
//出栈
ElementType stack_pop(LinkedStack* stack) {
if (is_empty(stack)) {
printf("error:Stack is empty.\n");
exit(1);
}
StackFrame* curr = stack->top;
ElementType data = curr->data;
stack->top = curr->next;
free(curr);
return data;
}
//访问栈顶元素
ElementType stack_peek(LinkedStack* stack) {
if (is_empty(stack)) {
printf("error:Stack is empty.\n");
exit(1);
}
ElementType data = stack->top->data ;
return data;
}
//打印栈
ElementType print_stack(LinkedStack* stack) {
StackFrame* curr = stack->top ;
while (curr) {
printf("%d", curr->data);
if (curr->next != NULL) {
printf(" -> ");
}
curr = curr->next;
}
printf("\n");
}
// 销毁链式栈
void stack_destroy(LinkedStack* stack) {
StackFrame* curr = stack->top;
while (curr) {
StackFrame* tmp = curr->next;
free(curr);
curr = tmp;
}
free(stack);
}
三、测试源
#include "stack.h"
int main(void) {
LinkedStack* stack = stack_create();
if (stack == NULL) {
printf("error:stack_create failed in main.\n");
exit(1);
}
stack_push(stack, 5);
stack_push(stack, 4);
stack_push(stack, 3);
stack_push(stack, 2);
stack_push(stack, 1);
printf("原始的栈为:\n");
print_stack(stack);
printf("第一次弹栈出的数值为:%d\n",stack_pop(stack));
printf("第二次弹栈出的数值为:%d\n", stack_pop(stack));
printf("弹栈两次后的栈为:\n");
print_stack(stack);
printf("访问栈顶元素为:%d\n", stack_peek(stack));
stack_destroy(stack);
//print_stack(stack);
return 0;
}
四、输出样例
总结
基本操作并不难,注意操作时的判空即可。
销毁时先销毁栈帧最后销毁结构体。