使用单链表来实现,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;
}
转载于:https://blog.51cto.com/xwandrew/2045455