1. 程式人生 > >簡單的C語言棧的實現程式碼

簡單的C語言棧的實現程式碼

#include <STDIO.H>
#include <MALLOC.H>
#include <assert.h>
#include <stdlib.h>


typedef int ElemType;
const int stackMaxSize = 50;
struct Stack{
ElemType *base;
ElemType *top;
int stacksize;
};


void initStack(Stack *S)
{
assert(S != NULL);
S->base = (ElemType *)malloc(sizeof(ElemType)*stackMaxSize);
if (NULL == S->base)
{
exit(0);
}
S->top = S->base;
S->stacksize = 0;
}


void DestoryStack(Stack *S)
{
assert(S != NULL);
if (S->base)
{
free(S->base);
}
S->base = S->top = NULL;
S->stacksize = 0;
}


void ClearStack(Stack *S)
{
assert(S != NULL);
if (S->base)
{
S->top = S->base;
S->stacksize = 0;
}
}


int isEmpty(Stack *S)
{
assert(S != NULL);
return !S->stacksize;
}


int StackLength(Stack *S)
{
assert(S != NULL);
return S->stacksize;
}


void getTop(Stack *S,ElemType *e)
{
assert(S != NULL);
assert (!isEmpty(S));
*e = S->base[S->stacksize-1];
}


void push(Stack *S,ElemType e)
{
assert(S != NULL);
assert(S->stacksize != stackMaxSize);
*(S->top) = e;
S->stacksize++;
S->top = &S->base[S->stacksize];
}


void pop(Stack *S,ElemType *e)
{
assert(S != NULL);
assert (!isEmpty(S));
*e = S->base[S->stacksize-1];
S->stacksize--;
S->top = &S->base[S->stacksize];
}


//遍歷棧
void stackTraverse(Stack *S,void (*visit)(ElemType e))
{
assert(S != NULL);
assert (!isEmpty(S));


int i=0;
while (i<S->stacksize)
{
visit(S->base[i]);
++i;
}
}


void visit(ElemType e)
{
printf("%d ",e);
}


int main(void)
{
Stack S;
ElemType arr[] = {1,2,3,4,5,6,7,8};
ElemType e;
initStack(&S);
int arrLength = sizeof(arr)/sizeof(arr[0]);
int i=0;
while(i< arrLength)
{
push(&S,arr[i++]);
}
printf("棧的大小:%d\n",StackLength(&S));
printf("從棧底訪問所有元素:");
stackTraverse(&S,&visit);
printf("\n出棧:");
while(!isEmpty(&S))
{
pop(&S,&e);
visit(e);
}
printf("\n23 壓棧");
push(&S,23);
getTop(&S,&e);
printf("\n獲取棧頂元素:%d",e);
printf("\n清空棧...\n");
ClearStack(&S);
printf("棧的大小:%d\n",StackLength(&S));
printf("\n銷燬棧...\n");
DestoryStack(&S);
return 0;

}

結果: