栈(顺序)

来源:互联网 发布:乐清市网络问效平台 编辑:程序博客网 时间:2024/06/15 22:53

栈的顺序实现

头文件

#ifndef SEQSTACK_H#define SEQSTACK_Htypedef void SeqStack;SeqStack* SeqStack_Create(int capacity);void SeqStack_Destroy(SeqStack* stack);void SeqStack_Clear(SeqStack* stack);int SeqStack_Push(SeqStack* stack,void* item);void* SeqStack_Pop(SeqStack* stack);void* SeqStack_Top(SeqStack* stack);int SeqStack_Size(SeqStack* stack);int SeqStack_Capacity(SeqStack* stack);#endif

源文件

#include "SeqStack.h"#include <malloc.h>#include <stdio.h>typedef unsigned int TSeqStackNode;typedef struct tag_SeqStack{    int capacity;    int length;    TSeqStackNode* node;}TSeqStack;SeqStack* SeqStack_Create(int capacity){    SeqStack* ret = NULL;    if(capacity >=0)    {        ret =  (SeqStack*)malloc(sizeof(TSeqStack)+sizeof(TSeqStackNode)*capacity);    }    if(ret != NULL)    {        ret->capacity = capacity;        ret->length = 0;        ret->node = (TSeqStackNode*)(ret+1);    }    return ret;}void SeqStack_Destroy(SeqStack* stack){    free(stack);}void SeqStack_Clear(SeqStack* stack){    TSeqStack* m_stack = (TSeqStack*)stack;    if(m_stack != NULL)    {        m_stack->length = 0;    }}int SeqStack_Push(SeqStack* stack,void* item){    TSeqStack* m_stack = (TSeqStack*)stack;    int ret = (m_stack!=NULL);    int i = 0;    ret = ret&&(m_stack->length+1 <= m_stack->capacity);    if(ret)    {        m_stack->node[m_stack->length] = (TSeqStackNode)item;        m_stack->length++;    }    return ret;}void* SeqStack_Pop(SeqStack* stack){    TSeqStack* m_stack = (TSeqStack*)stack;    TSeqStack* ret = NULL;    ret = m_stack->node[SeqStack_Size(m_stack)-1]    m_stack->length--;    return ret;}void* SeqStack_Top(SeqStack* stack){    TSeqStack* m_stack = (TSeqStack*)stack;    return m_stack->node[SeqStack_Size(m_stack)-1];}int SeqStack_Size(SeqStack* stack){    TSeqStack* m_stack = (TSeqStack*)stack;    int ret = -1;    if(m_stack != NULL)    {        ret = m_stack->length;    }    return ret;}int SeqStack_Capacity(SeqStack* stack){    TSeqStack* m_stack = (TSeqStack*)stack;    int ret = -1;    if(m_stack != NULL)    {        ret = m_stack->capacity;    }    return ret;}
原创粉丝点击