数据结构-栈的实现

Stack是对于数据结构,数据存储非常重要的,其实对于自己而言也是在学习之中。我认为学习者要更多去将实际而转化成计算机的代码进而实现其价值。这是基础,有了基础我认为处理一些现实问题(抽象成计算机模型)才会有更好的办法。例如解决NP问题等。

实现Stack,你首先应该理解它的构造,其原理其实有很多人都明白,我是用C去实现,(我认为想我们这种学习者应该减少用C++,java等面向对象语言,它们都有封装好的Stack,Queue等,不利于深入理解和学习)

数据构造:

typedef char  Data;

#define InISize 20

#define AppSize 50

typedef struct Stack{

    int Capacity;

    Data*base;

    Data*top;

}Stack;

初始化Sack;

void IniStack(Stack *s)

{

    s->base=(Data*)malloc(InISize*sizeof(Data));

    if(!s->base)//防止下溢

        return ;

    s->top=s->base;

    s->Capacity=InISize;

}

数据数量:

int lengthStack(Stack *s)

{

    return (int)(s->top-s->base);

}

栈为空:

int EmptyStack(Stack *s)

{

    if(s->top==s->base)

        return 0;

    else

        return 1;

}

入栈:

void Push(Stack *s,Data d)

{

    

    if(s->top-s->base>=s->Capacity)

    {

        s->base=(Data *)realloc(s->base,AppSize*sizeof(Data));

        if(!s->base)

            return ;

        s->top=s->base+s->Capacity;

        s->Capacity=AppSize+InISize;

    }

    *(s->top)=d;

    s->top++;

}

出栈:

这里要将数据读出到e这个地址中去,并且指针下移;

void pop(Stack *s,Data *D)

{

    if(s->top==s->base)

        return ;

    s->top--;

    *D=*(s->top);

}

释放栈:

void destroyStack(Stack *s)

{

    free(s->base);

    s->top=s->base;

    s->StackSize=0;

}

打印栈:

void Print(Stack s)

{

    if(s.top==s.base)

    {

        

        printf("the Stack is empty");

        return;

    }

    else

    {

        s.top--;

        while(s.top!=s.base)

        {

            printf("%c ",*s.top);

            s.top--;

        }

        printf("%c ",*s.top);

    }

}

清空栈:

void ClearStack(Stack *s)

{

    s->top=s->base;

}

测试用例:

Stack S;

    IniStack(&S);

    Data test;

    char a[4]={'a','b','c','d'};

    for(int i=0;i<4;i++)

        Push(&S, a[i]);

    printf("the orginal data is:");

    puts(a);

    printf("the size of Stack is %d",StackSize(&S));

    printf("\nPrint Stack in Screen:");

    Print(S);

    printf("\n");

    pop(&S, &test);

    printf("pop from the stack:%c\n",test);

    printf("the size of Stack is %d",StackSize(&S));

    printf("\nPrint Stack in Screen:");

    Print(S);

    printf("\n");

    ClearStack(&S);

    Print(S);

    printf("\n");

请大家指出学生的错误之处,帮助学生进步!



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值