用双向链表实现一个栈
生活随笔
收集整理的這篇文章主要介紹了
用双向链表实现一个栈
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
前面我們已經造好了一個輪子——雙向鏈表,那么我們可以利用這個輪子做一個棧。
入棧:我們采用鏈表的頭插
獲得棧頂的元素:把頭部元素拷貝到用戶數據區
出棧:先把頭部的元素拷貝到用戶數據區,然后刪除這個節點
好的,看一下頭文件吧。
#pragma once #include "dlist.h"struct stack_info {struct dlist_info *dlist;// 雙向鏈表的指針int (*push)(struct stack_info *info, const void *data, size_t size);//入棧int (*top)(struct stack_info *info,void *data, size_t size);//獲得棧頂的元素int (*pop)(struct stack_info *info,void *data, size_t size);//出棧int (*is_empty)(struct stack_info *info); };void stack_init(struct stack_info *info); void stack_destroy(struct stack_info *info);接下來看實現。 static int stack_push(struct stack_info *info, const void *data, size_t size) {info->dlist->add_head(info->dlist, data, size);return 0; }是不是很簡單呢?直接頭插就可以了。 static int stack_is_empty(struct stack_info *info) {return dlist_is_empty(info->dlist); }
static int stack_top(struct stack_info *info,void *data, size_t size) {if (stack_is_empty(info)) {return -1;}else{memcpy(data, info->dlist->head->next->data, size);}return 0; }top方法,注意,這個方法只會得到棧頂元素的值,并不會刪除棧頂的元素。
static int stack_pop(struct stack_info *info,void *data, size_t size) {if (stack_top(info, data, size) < 0) {return -1;// means empty}else{info->dlist->del(info->dlist->head->next);}return 0; }pop方法,不用多說。
構造和析構:
void stack_init(struct stack_info *info) {info->dlist = (struct dlist_info *)malloc(sizeof(struct dlist_info));if (info->dlist != NULL) {dlist_init(info->dlist);}else{printf("stack initialize failed.\n");return ;}info->push = stack_push;info->pop = stack_pop;info->top = stack_top;info->is_empty = stack_is_empty; }void stack_destroy(struct stack_info *info) {dlist_destroy(info->dlist);free(info->dlist); }最后我們看一下單元測試 void print_student(void* data) {struct student *p = (struct student *)(data);printf("Name: %15s Age:%d\n",p->name,p->age);}START_TEST(case_2) {struct student students[] = {{"WangDong",18},{"LiuMing",19},{"SunYazhou",21},{"QingYun",27}};struct stack_info stack;stack_init(&stack);struct student stu_tmp;ck_assert_msg(stack.is_empty(&stack)==1);int i = 0;for(;i<(sizeof(students)/sizeof(students[0]));++i)stack.push(&stack,students+i,sizeof(students[0]));while(stack.is_empty(&stack)!=1){stack.pop(&stack,&stu_tmp,sizeof(students[0]));print_student(&stu_tmp);}} END_TEST 簡單的測一下pop和push,結果如下:
Running suite(s): stack_(using_dlist)
Name: ? ? ? ? QingYun? Age:27
Name: ? ? ? SunYazhou? Age:21
Name: ? ? ? ? LiuMing? Age:19
Name:? ? ? ? WangDong? Age:18
100%: Checks: 1, Failures: 0, Errors: 0
(完)
總結
以上是生活随笔為你收集整理的用双向链表实现一个栈的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 分享一篇关于社区团购的竞品分析
- 下一篇: container_of 和 offse