栈堆的定义与操作(last in,first out list)

1.顺序存储:

struct stack_order{
    elementtype data[max];
    int max;//最大容量
    int top;//栈顶位置
}
typedef struct stack_order* stack;

//初始化
stack initial(int max){
    stack s=(stack)malloc(sizeof(struct stack_order));
    s->data[0]=0;
    s->max=max;
    s->top=-1;
    return s;
}

//判断栈是否满了
bool isfull(stack s){
    return (s->top+1==max);
}

//将元素x压入栈中
bool push(stack s,elementtype x){
    if (isfull(stack s))
        return false;//栈满,无法存入
    else{
        s->data[++(s->top)]=x;
        return true;//存入成功
    }
}

//判断栈是否为空
bool isempty(stack s){
    return (s->top==-1);
}

//出栈
bool pop(stack s){
    if (isempty(s))
        return false;//栈为空
    else 
        return (s->data[(s->top)--]);//出栈成功
}

2.链式存储:

typedef struct stack_chain* stack;
struct stack_chain{
    elementtype data;
    stack next;
}

//初始化
stack initial(){
    stack s=(stack)malloc(sizeof(struct stack_chain));
    s->next=null;
    s->data=-1;
    return s;
}

//判断栈是否为空
bool isempty(stack s){
    return (s->next==null);
}

//将元素x压入栈中
bool push(stack s,elementtype x){
    stack p=(stack)malloc(sizeof(struct stack_chain));
    p->next=s->next;
    p->data=x;
    s->next=p;
    return true;
}

//出栈
elementtype pop(stack s){
    if (isempty(s))
        return false;
    else{
        stack p=s;
        s=p->next;
        elementtype temp=p->data;
        free(p);
        return temp;
    }
}