c語言實現數據結構中的棧

    以下我用c語言實現數據結構中的棧

 
 
 
 
#pragma once 
 
#ifndef _SIZE_H 
#define _SIZE_H 
 
#define STACK_INIT_SIZE          100 
#define STACKINCREATE            20 
 
#endif 
 
#ifndef _ELEMTYPE_H 
#define _ELEMTYPE_H 
 
typedef int ElemType;            
                                 
 
#endif 
 
#ifndef _STDLIB_H 
#define _STDLIB_H 
 
#include <stdlib.h> 
 
#endif 
 
#ifndef _STACK_H 
#define _STACK_H 
 
typedef struct 
{ 
    ElemType * p_base;      
    ElemType * p_top;      
    int StackSize;          
}Stack; 
 
#endif

 
 
 
 
 
#include "stdafx.h" 
 
bool InitStack(Stack &S); 
 
bool DestoryStack(Stack &S); 
 
bool ClearStack(Stack &S); 
 
bool StackEmpty(const Stack &S); 
 
int StackLength(const Stack &S); 
 
bool GetTop(const Stack &S,ElemType &e); 
 
bool Push(Stack &S,ElemType e); 
 
bool Pop(Stack &S,ElemType &e); 
 
void StackTraverse(Stack &S,void(* visit)(ElemType e));


 
 
 
 
 
#include "Stack.h"
 
 
 
 
 
 
bool InitStack(Stack &S)
{
    S.p_base=(ElemType *)malloc(STACK_INIT_SIZE*sizeof(ElemType));
    if(S.p_base==NULL)
        return false;
    S.p_top=S.p_base;
    S.StackSize=STACK_INIT_SIZE;
    return true;
}
 
 
 
 
 
 
bool DestoryStack(Stack &S)
{
    free(S.p_base);
    S.p_base=NULL;
    S.p_top=NULL;
    S.StackSize=0;
    return true;
}
 
 
 
 
 
bool ClearStack(Stack &S)
{
    S.p_top=S.p_base;
    return true;
}
 
 
 
 
 
 
 
bool StackEmpty(const Stack &S)
{
    if(S.p_top==S.p_base)
        return true;
    else
        return false;
}
 
 
 
 
 
 
 
int StackLength(const Stack &S)
{
    return S.p_top-S.p_base;
}
 
 
 
 
 
 
 
bool GetTop(const Stack &S,ElemType &e)
{
    if(StackEmpty(S))
    {
        e=NULL;
        return false;
    }
    else
    {
        e= *(S.p_top-1);
        return false;
    }
}
 
 
 
 
 
 
 
bool Push(Stack &S,ElemType e)
{
    if(StackLength(S)>=S.StackSize)
    {
        S.p_base=(ElemType *)realloc(S.p_base,(S.StackSize+STACKINCREATE)*sizeof(ElemType));
        if(S.p_base==NULL)
            return false;
        S.p_top=S.p_base+S.StackSize;
        S.StackSize+=STACKINCREATE;
    }
    *S.p_top=e;
    S.p_top++;
    return true;
}
 
 
 
 
 
 
bool Pop(Stack &S,ElemType &e)
{
    if(StackEmpty(S))
    {
        e=NULL;
        return false;
    }
    else
    {
        e=*(S.p_top-1);
        S.p_top--;
        return true;
    }
}
 
 
 
 
void StackTraverse(Stack &S,void(* visit)(ElemType e))
{
    if(StackEmpty(S))
        return;
    else
    {
        ElemType * temp=S.p_top;
        while(temp!=S.p_base)
        {
            (* visit)(*(temp-1));
            temp--;
        }
    }
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章