Chinaunix首页 | 论坛 | 博客
  • 博客访问: 342639
  • 博文数量: 72
  • 博客积分: 2130
  • 博客等级: 大尉
  • 技术积分: 857
  • 用 户 组: 普通用户
  • 注册时间: 2008-09-05 16:10
文章分类

全部博文(72)

文章存档

2010年(5)

2009年(14)

2008年(53)

分类: C/C++

2008-10-08 10:33:22

#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;
}






阅读(1286) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~