From 3698865b3228259ab604d38bedfe95b60c26701f Mon Sep 17 00:00:00 2001 From: Gonglja Date: Mon, 16 Jan 2023 16:27:55 +0800 Subject: [PATCH] fix(codes/c): Fix linkedlist_stack.c memory release problem --- codes/c/chapter_stack_and_queue/linkedlist_stack.c | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/codes/c/chapter_stack_and_queue/linkedlist_stack.c b/codes/c/chapter_stack_and_queue/linkedlist_stack.c index 5f09b8cf8..a63ea1919 100644 --- a/codes/c/chapter_stack_and_queue/linkedlist_stack.c +++ b/codes/c/chapter_stack_and_queue/linkedlist_stack.c @@ -20,6 +20,16 @@ void newLinkedListStack(LinkedListStack* stk) { stk->size = 0; } +/* 析构函数 */ +void delLinkedListStack(LinkedListStack* stk) { + while(stk->stackTop) { + ListNode *n = stk->stackTop->next; + free(stk->stackTop); + stk->stackTop = n; + } + stk->size = 0; +} + /* 获取栈的长度 */ int size(LinkedListStack* stk) { assert(stk); @@ -64,6 +74,7 @@ void pop(LinkedListStack* stk) { int main() { /* 初始化栈 */ LinkedListStack stack; + /* 构造函数 */ newLinkedListStack(&stack); /* 元素入栈 */ @@ -93,5 +104,7 @@ int main() { bool isEmpty = empty(&stack); printf("栈是否为空 = %s\r\n", isEmpty ? "yes" : "no"); + /* 析构函数 */ + delLinkedListStack(&stack); return 0; }