温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C语言实现链式栈(LinkStack)

发布时间:2020-06-21 11:52:07 来源:网络 阅读:593 作者:暮色伊人 栏目:编程语言

使用单链表来实现,push,pop均在链表头部进行

linkStack.h

#ifndef LINK_STACK_H
#define LINK_STACK_H
#include <stdlib.h>
#include <stdio.h>
#include <memory.h>
#include <stdbool.h>

typedef void LinkStack;

LinkStack* LinkStack_Create();

void LinkStack_Destroy(LinkStack* stack);

void LinkStack_Clear(LinkStack* stack);

int LinkStack_Push(LinkStack* stack, void* item);

void* LinkStack_Pop(LinkStack* stack);

void* LinkStack_Top(LinkStack* stack);

int LinkStack_Size(LinkStack* stack);

bool LinkStack_isEmpty(LinkStack* stack);

#endif //LINK_STACK_H

linkStack.c

#include"linkStack.h"
#include"linkedList.h"

typedef struct NodeItem {
    LinkedListNode node;
    void* item;
}StackItem;

LinkStack* LinkStack_Create() {
    return LinkedList_Create();
}

void LinkStack_Destroy(LinkStack* stack) {
    LinkStack_Clear(stack);
    LinkedList_Destory((LinkedList*)stack);
    return;
}

void LinkStack_Clear(LinkStack* stack) {
    if (stack == NULL) {
        return;
    }
    while (LinkStack_Size(stack) > 0) {
        LinkStack_Pop(stack);
    }
}

int LinkStack_Push(LinkStack* stack, void* item) {
    StackItem* element = (StackItem*)malloc(sizeof(StackItem));
    element->node.next = NULL;
    if (element == NULL) {
        fprintf(stderr,"malloc memeory error.\n");
        return - 1;
    }
    memset(element, 0, sizeof(StackItem));
    element->item = item;
    int ret = LinkedList_Insert((LinkedList*)stack, &element->node, 0);
    if (ret != 0) {
        fprintf(stderr,"LinkedList_Insert() error.\n");
        if (element != NULL) {
            free(element);
        }
        return -2;
    }
    return 0;
}

void* LinkStack_Pop(LinkStack* stack) {
    if (stack == NULL) {
        return NULL;
    }

    StackItem* element = (StackItem*)LinkedList_Delete((LinkedList*)stack, 0);
    if (element == NULL) {
        return NULL;
    }

    void* item = element->item;
    free(element);
    return item;
}

void* LinkStack_Top(LinkStack* stack) {
    if (stack == NULL) {
        return NULL;
    }
    StackItem* element = (StackItem*)LinkedList_Get((LinkedList*)stack, 0);
    if (element == NULL) {
        return NULL;
    }
    return element->item;
}

int LinkStack_Size(LinkStack* stack) {
    if (stack == NULL) {
        return 0;
    }
    return LinkedList_Length((LinkedList*)stack);
}

bool LinkStack_isEmpty(LinkStack* stack) {
    return LinkStack_Size(stack) == 0;
}
向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI