(七)线性堆栈

/****************************************
堆栈操作:<EMPTY><PUSH><POP><TOP>
用数组S[0,n-1]来实现一个至多有n个元素的栈。

STACK_EMPYT(S) //判断栈是否为空
    if top[S]=-1
        then return ture
        else return false

PUSH(S,x) //将元素x压入栈中
    if top[S]=n-1
        then error "stack overflow"
    top[S] <—— top[S]+1
    S[top[S]] <—— x
    
POP(S) //从栈顶弹出一个元素
    if STCK_EMPTY(S)
        then error "stack underflow"
    else top[S] <—— top[S]-1
    return S[top[S]+1]

top(S) //获取栈顶元素,但不弹出栈顶元素
    if STCK_EMPTY(S)
        then error "stack underflow"
    return S[top[S]]
****************************************/
#include <stdio.h>
#include <stdlib.h>
#define STACKSIZE 1024
#define MAX_INT ~(1<<31)
typedef struct {
    int *data;
    int top;
}stack;
int stack_empty(stack *s)
{
    return (s->top==-1);
}
void push(stack *s,int x)
{
    if(s->top>=STACKSIZE-1)
        return;
    s->top++;
    s->data[s->top]=x;
}
int pop(stack *s)
{
    if(stack_empty(s))
        return MAX_INT;
    s->top--;
    return s->data[s->top+1];
}
int top(stack *s)
{
    if(stack_empty(s))
        return MAX_INT;
    return s->data[s->top];
}
//初始化一个栈
stack* init_stack(int size)
{
    stack *pstack=(stack*)malloc(sizeof(stack));
    pstack->data=(int*)malloc(size*sizeof(int));
    pstack->top=-1;
    return pstack;
}
//释放栈资源,在使用完栈后,调用此函数
void fini_stack(stack *pstack)
{
    if(pstack->data)
        free(pstack->data);
    if(pstack)
        free(pstack);
}
int main()
{
    stack *pstack=init_stack(STACKSIZE);
    int i;
    for(i=0;i<10;++i)
        push(pstack,i);
    for(i=0;i<=pstack->top;++i)
        printf("%d ",pstack->data[i]);
    pop(pstack);
    pop(pstack);
    printf("%d ",top(pstack));
    for(i=0;i<=pstack->top;++i)
        printf("%d ",pstack->data[i]);
  fini_stack(pstack);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值