棧的實現(C語言實現)
//頭文件
#include
/*====================
棧 數據結構
利用數組實現
====================*/
#define MAX 100
#define ok 1
#define error 0
typedef struct Stack
{
int data[MAX];
int top; //棧頂
int bottom; //棧底
}Stack,*STACK;
//初始化棧
int InitStack(STACK stack);
//銷毀
int DestroyStack(STACK stack);
//清空
int ClearStack(STACK stack);
//棧空
int StackEmpty(STACK stack);
//獲取棧頂元素
int GetTop(STACK stack,int* elem);
//壓棧
int Push(STACK stack,int* elem);
//出棧
int Pop(STACK stack,int* elem);
//返回棧中元素長度
int StackLength(STACK stack,int* len);
//打印棧中元素
int PrintStack(STACK stack);
//棧滿
int StackFull(STACK stack);
//main函數中實現
#include "stack.h"
int main()
{
int num=10, num1, i=0,j=0;
Stack stack;
int initFlag=InitStack(&stack);
if(!initFlag)
return 0;
for(num1=0;num1<10;num1++)
Push(&stack,&num1);
/*
int pushFlag=Push(&stack,&num);
if(!pushFlag)
return 0;
*/
// ClearStack(&stack);
for(;i<10;i++)
{
int flag=Pop(&stack,&num1);
if(flag)
printf("%d ",num1);
else
printf("Pop error");
}
int lenFlag=StackLength(&stack,&num1);
if(lenFlag)
printf("len=%d ",num1);
else
printf("StackLength error");
/*
int getFlag=GetTop(&stack,&num1);
if(getFlag)
printf("%d ",num1);
*/
PrintStack(&stack);
return 0;
}
//初始化棧
int InitStack(STACK stack)
{
if(stack==NULL)
return error;
stack->bottom=stack->top=0;
return ok;
}
//壓棧
int Push(STACK stack,int* elem)
{
int flag=StackFull(stack);
if(!flag)
return error;
stack->data[stack->top] =*elem;
++stack->top;
return ok;
}
//打印棧中所有元素
int PrintStack(STACK stack)
{
int i=0;
int flag=StackEmpty(stack);
if(!flag)
return error;
for(i=0;itop;i++)
{
printf("%d ",stack->data[i]);
}
printf("\n");
return ok;
}
//棧空
int StackEmpty(STACK stack)
{
if(stack==NULL || stack->top==stack->bottom)
return error;
else
return ok;
}
//出棧
int Pop(STACK stack,int* elem)
{
int flag=StackEmpty(stack);
if(!flag)
return error;
*elem=stack->data[stack->top-1];
--stack->top;
return ok;
}
//棧滿
int StackFull(STACK stack)
{
if(stack==NULL || stack->top>MAX)
return error;
else
return ok;
}
//銷毀
int DestroyStack(STACK stack)
{
if(stack==NULL)
return ok;
else
{
stack->top=stack->bottom;
stack=NULL;
return ok;
}
}
//清空
int ClearStack(STACK stack)
{
int flag=StackEmpty(stack);
if(!flag)
return error;
else
{
stack->top=stack->bottom;
return ok;
}
}
//獲取棧頂元素
int GetTop(STACK stack,int* elem)
{
int flag=StackEmpty(stack);
if(!flag)
return error;
*elem=stack->data[stack->top-1];
return ok;
}
//返回棧中元素長度
int StackLength(STACK stack,int* len)
{
if(stack==NULL)
return error;
if(stack->top==stack->bottom)
{
*len=0;
return ok;
}
else
{
*len=stack->top;
return ok;
}
}