【数据结构与算法分析】 第三章 栈

栈ADT

1栈模型

栈是限制插入和删除只能在一个位置上进行的表,该位置是表的末端,叫做栈顶(top),对栈的基本操作有push(进栈)和pop(出栈),前者相当于插入,后者则是删除最后插入的元素。

栈是后进先出的(LIFO)表,一般的模型中,存在某个元素位于栈顶,而该元素是唯一的可见元素。只有栈顶元素是可以访问的

2 栈的实现

栈是一个表,因此任何实现表的方法都能实现栈。两种方法实现:一种是指针,一种是使用数组

2.1 栈的数组实现

栈的数组实现是目前用的最多的方法

栈的声明:

#ifndif _Stack_h
struct StackRecord;
typedef struct StackRecord *Stack;
int IsEmpty(Stack S);
int IsFull(Stack S);
Stack CreateStack(int MaxElements);
void DisposeStack(Stack S);
void MakeEmpty(Stack S);
void Push(ElementType X,Stack S);
ElementType Top(Stack S);
void Pop(Stack S);
ElementType TopAndPop(Stack S);
#endif

#define EmptyTOS(-1)
#define MinStackSize(5)

struct StackRecord
{
    int Capacity;
    int TopOfStack;
    ElementType *Array;
};

 栈的创建:

Stack CreatStack(int MaxElements)
{
    Stack S;
    if(MaxElements<MinStackSize)
        Error("Stack size is too small");
    S=malloc(sizeof(struct StackRecord));
    if(S==NULL)
        FatalError("out of space");
    S->Array=malloc(sizeof(ElementType)*MaxElements)
    if(S->Array=NULL)
        FatalError("out of space");
    S->Capacity=MaxElements;
    MakeEmpty(S);
    
    return S;
}

释放栈:

void DisposeStack(Stack S)
{
    if(S!=NULL)
    {
        free(S);
        free(S->Array);
    }

}

检测一个栈是否空栈:

int IsEmpty(Stack S)
{
    return S->TopOfStack == EmptyTOS;
}

创建一个空栈:

void MakeEmpty(Stack S)
{
    S->TopOfStack=EmptyTOS;
}

进栈:

扫描二维码关注公众号,回复: 2778346 查看本文章
void Push(ElementType X,Stack S)
{
    if(IsFull(S))
        Error("Full stack");
    else
        S->Array[++S->TopOfStack]=X;
}

出栈:

void Pop(Stack S)
{
    if(IsEmpty(S))
        Error("Empty stack");
    else
        S->TopOfStack--;
}

给出栈顶元素并出栈:

ElementType TopAndPop(Stack S)
{
    if(!IsEmpty(S))
        return S->Array[S->TopOfStack--];
    else
    {
        Error("empty stack");
        return 0;
     }     
}

猜你喜欢

转载自blog.csdn.net/zhangxiafll/article/details/81672777
今日推荐