C语言实现顺序栈(SeqStack)

使用数组来保存数据,使用二级指针来保存栈中元素的地址

创新互联建站是一家专注于网站设计、成都网站建设与策划设计,安次网站建设哪家好?创新互联建站做网站,专注于网站建设10余年,网设计领域的专业建站公司;建站业务涵盖:安次等地区。安次做网站价格咨询:18980820575

seqStack.h

#ifndef SEQ_STACK_H
#define SEQ_STACK_H
#include
#include
#include
#include

typedef void SeqStack;

SeqStack* Stack_Create(int cap);

void Stack_Destroy(SeqStack* stack);

void Stack_Clear(SeqStack* stack);

int Stack_Push(SeqStack* stack, void* item);

void* Stack_Pop(SeqStack* stack);

void* Stack_Top(SeqStack* stack);

int Stack_Size(SeqStack* stack);

bool Stack_isFull(SeqStack* stack);

bool Stack_isEmpty(SeqStack* stack);
#endif //SEQ_STACK_H

seqStack.c

#include"seqStack.h"

typedef struct SeqStackStruct {
    int size;
    int cap;
    unsigned int **data;
}MySeqStack;

SeqStack* Stack_Create(int cap) {
    MySeqStack* myStack = (MySeqStack*)malloc(sizeof(MySeqStack));
    if (myStack == NULL) {
        fprintf(stderr,"malloc stack space error.\n");
        return NULL;
    }
    myStack->data = (unsigned int**)malloc(cap * sizeof(unsigned int*));
    memset(myStack->data, 0, cap * sizeof(unsigned int*));
    myStack->size = 0;
    myStack->cap = cap;
    return (void *)myStack;
}

void Stack_Destroy(SeqStack* stack){
    MySeqStack *myStack = (MySeqStack *)stack;
    myStack->size = 0;
    myStack->cap = 0;
    free(myStack);
    myStack = NULL;
}

void Stack_Clear(SeqStack* stack) {
    MySeqStack *myStack = (MySeqStack *)stack;
    myStack->size = 0;
}

int Stack_Push(SeqStack* stack, void* item) {
    if (stack == NULL) {
        return -1;
    }
    MySeqStack *myStack = (MySeqStack *)stack;
    if (myStack->size >= myStack->cap) {    
        fprintf(stderr, "stack is Full.\n");
        return -2;
    }
    myStack->size++;
    myStack->data[myStack->size-1] = (unsigned int*)item;

}

bool Stack_isFull(SeqStack* stack) {
    if (stack == NULL) {
        return false;
    }
    MySeqStack *myStack = (MySeqStack *)stack;
    return myStack->size == myStack->cap;
}

bool Stack_isEmpty(SeqStack* stack) {
    if (stack == NULL) {
        return false;
    }
    MySeqStack *myStack = (MySeqStack *)stack;
    return myStack->size == 0;
}

void* Stack_Pop(SeqStack* stack) {
    if (stack == NULL) {
        return;
    }
    MySeqStack *myStack = (MySeqStack *)stack;
    void *item = (void *)myStack->data[myStack->size - 1];
    myStack->data[myStack->size - 1] = NULL;
    myStack->size--;
    return  item;
}

void* Stack_Top(SeqStack* stack) {
    if (stack == NULL) {
        return;
    }
    MySeqStack *myStack = (MySeqStack *)stack;
    return (void *)myStack->data[myStack->size - 1];
}

int Stack_Size(SeqStack* stack) {
    if (stack == NULL) {
        return 0;
    }
    MySeqStack *myStack = (MySeqStack *)stack;
    return myStack->size;
}

名称栏目:C语言实现顺序栈(SeqStack)
URL网址:http://ybzwz.com/article/gieood.html