栈的顺序存储

栈只是一种具有特殊规则的线性表,它的操作原理和线性表几乎相同。

栈的链式存储

#include<stdio.h>
#include<malloc.h>

#define INIT_SIZE 1
#define INCREASE 10

typedef int ElemType;

typedef struct 
{
    ElemType *top;
    ElemType *base;
    int length;
    int size;
    /* data */
}Stack;

void init_stack(Stack *p){
    p->base = p->top = (ElemType *)malloc(INIT_SIZE*sizeof(ElemType));
    p->length = 0;
    p->size = INIT_SIZE;
}

void show(Stack *p){
    if(p->top == p->base){
        printf("THE STACK IS NULL");
        return ;
    }

    //要把top指针的指向传给一个中间点,通过该点实现遍历
    ElemType *q = p->top-1;
    
    while(q >= p->base){
        printf("%2d",*q);
        q--;
    }
    printf("\n");
}

void push(Stack *p, ElemType e){
    if(p->length >= p->size){
        p->base = (ElemType *)realloc(p->base,(p->size+INCREASE)*sizeof(ElemType));
        p->top = p-> base + p->length;
        p->size += INCREASE;
    }
    *p->top++ = e;
    p->length++;
}


void pop(Stack *p, ElemType *e){
    if(p->top == p->base){
        printf("THE STACK IS NULL");
        return ;
    }
    *e = *--p->top;
    p->length--;
}

int main(){
    ElemType m;
    Stack stack;
    init_stack(&stack);

    push(&stack,2);
    push(&stack,4);
    show(&stack);

    pop(&stack,&m);
    show(&stack);
    
    printf("%d\n",m);
    return 0; 
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值