From 3839f47ac0c5e056911d19ea5079ce0a2ce37dab Mon Sep 17 00:00:00 2001 From: Gonglja Date: Fri, 13 Jan 2023 05:48:29 +0800 Subject: [PATCH] feat(codes/c): update linkedlist_stack.c some code --- .../linkedlist_stack.c | 47 +++++++++++++++++-- 1 file changed, 42 insertions(+), 5 deletions(-) diff --git a/codes/c/chapter_stack_and_queue/linkedlist_stack.c b/codes/c/chapter_stack_and_queue/linkedlist_stack.c index e190d3d63..fe457afd9 100644 --- a/codes/c/chapter_stack_and_queue/linkedlist_stack.c +++ b/codes/c/chapter_stack_and_queue/linkedlist_stack.c @@ -14,27 +14,64 @@ struct LinkedListStack { typedef struct LinkedListStack LinkedListStack; void new(LinkedListStack* stk) { + // 创建头结点 + stk->stkTop = (ListNode *)malloc(sizeof(ListNode)); + stk->stkTop->next = NULL; + stk->stkTop->val = 0; + // 初始化栈大小 + stk->stkSize = 0; } size_t size(LinkedListStack* stk) { - + assert(stk); + return stk->stkSize; } bool empty(LinkedListStack* stk) { - + assert(stk); + return size(stk) == 0; } void push(LinkedListStack* stk, int num) { - + assert(stk); + + // 创建一个新结点 + ListNode *n = (ListNode *)malloc(sizeof(ListNode)); + ListNode *h; + n->next = NULL; + n->val = num; + + // 遍历链表,将新结点挂在最后面 + h = stk->stkTop; + while(h && h->next) { + h = h->next; + } + h->next = n; + + // 栈大小自增 + stk->stkSize++; } void pop(LinkedListStack* stk) { - + assert(stk); + ListNode *h = stk->stkTop; + ListNode *n; + // 找到倒数第一个结点 h -> (h->next) -> (h->next->next) + while(h && h->next && h->next->next) { + h = h->next; + } + + // 先保存倒数个结点,断开 + n = h->next; + h->next = NULL; + + // 删除保存的结点 + free(n); } int top(LinkedListStack* stk) { - + assert(stk); } int main() {