堆栈

1.       栈的概念

栈(Stack):是限制在表的一端进行插入和删除操作的线性表。又称为后进先出LIFO(Last In First Out)或先进后出FILO(First In Last Out)线性表。

栈顶(Top):允许进行插入、删除操作的一端,又称为表尾。

栈底(Bottom):是固定端,又称为表头。

空栈:当表中没有元素时称为空栈。

2.       线性堆栈实现

#ifndef _STACK_H_
#define _STACK_H_

#define TRUE    1
#define FALSE    0
#define    OVERFLOW    -2
#define STACK_SIZE    5
#define STACKINCREMENT    2

typedef    int    Boolean;
typedef char    ElemType;

typedef struct sqstack
{
    ElemType *bottom;
    ElemType *top;
    int    size;
}SqStack;

#endif
stack.h
#include<stdio.h>
#include<stdlib.h>
#include"stack.h"

Boolean    init(SqStack *s);
Boolean push(SqStack *s,ElemType e);
Boolean pop(SqStack *s, ElemType *e);
int main(void)
{
    SqStack stack,*s;
    int i;
    s=&stack;
    if(init(s))
     printf("InitSuccess!\n");
    ElemType e = 'a';
    for(i=0;i<20;i++){
    e++;
        
        if(push(s,e))
            printf("stackSize:%d,\t%c\n",s->size,e);
    }
    while(pop(s,&e)){
    printf("pop()success:%c\n",e);
    }
    return 0;
}

Boolean init(SqStack *s)
{
    s->bottom=(ElemType *)malloc(STACK_SIZE*sizeof(ElemType));
    if(!s->bottom)  return FALSE;
    s->top=s->bottom;
    s->size=STACK_SIZE;
    return TRUE;
}

Boolean push(SqStack *s,ElemType e)
{
    if(s->top - s->bottom>=s->size-1)
    {
        s->bottom=(ElemType *)realloc(s->bottom,(s->size+STACKINCREMENT)*sizeof(ElemType));
    if(!s->bottom) return FALSE;
    s->top=s->bottom+s->size-1;
     s->size+=STACKINCREMENT;
    }
    *s->top=e;
    s->top++;
    return TRUE;
}

Boolean pop(SqStack *s,ElemType *e){
    if(s->top<=s->bottom)  return FALSE;
    s->top--;
    *e=*s->top;
    return TRUE;
}
View Code

 

posted @ 2013-08-16 16:54  ydp  阅读(260)  评论(0编辑  收藏  举报