#include
#include
#include
#define STACK_INCREMENT 10;
typedef char DataType;
typedef struct stack
{
DataType *data;
int top;
}Stack;
static size_t StackSize;
void StackCreate(Stack *S, size_t size)
{
StackSize = size;
if((S->data = (DataType *)malloc(StackSize*sizeof(DataType)))==NULL)
{
printf("memory alloc error");
exit(-1);
}
S->top = -1;
}
void StackDestroy(Stack *S)
{
free(S->data);
S->data = NULL;
}
int StackFull(Stack *S)
{
return S->top==StackSize-1;
}int StackEmpty(Stack *S)
{
return S->top==-1;
}
void push(Stack *S, DataType value)
{
if(StackFull(S))
{
StackSize = StackSize + STACK_INCREMENT;
S->data = (DataType *)realloc(S->data,StackSize*sizeof(DataType));
}
S->top++;
*(S->data+S->top) = value;
}
void pop(Stack *S)
{
if(StackEmpty(S))
{
printf("Stack is empty!\n");
exit(-1);
}
S->top--;
}
DataType top(Stack *S)
{
if(StackEmpty(S))
{
printf("Stack is empty!\n");
exit(-1);
}
return *(S->data+S->top);
}
DataType StackPrint(Stack *S)
{
int count = S->top;
printf("The elements of stack are: \n");
while(count != -1)
{
printf("%4c",*(S->data+count));
count--;
}
printf("\n");
}
int main(void)
{
Stack *S = (Stack *)malloc(sizeof(Stack));
StackCreate(S,5);
push(S,'a');
push(S,'b');
push(S,'c');
push(S,'d');
push(S,'e');
push(S,'f');
push(S,'g');
printf("The number of stack elements are :%d\n",S->top+1);
StackPrint(S);
printf("The top elements of the stack is :%c\n",top(S));
printf("after two elements is pop,\n");
pop(S);
pop(S);
printf("the number of stack elements are :%d\n",S->top+1);
StackPrint(S);
printf("The top elements of the stack is :%c\n",top(S));
printf("%4d\n",StackSize);
StackDestroy(S);
return 0;
}
阅读(1290) | 评论(0) | 转发(0) |