栈的实现

1. 栈的抽象结构基本操作

操作 | 解释

  • | -
    MakeNull(S) | 将栈S置为空
    Top(S) | 返回栈顶元素
    Pop(S) | 删除栈顶元素
    Push(x, S) | 将x插入S的栈顶
    Empty(S) | 若S为空,返回true

2. 栈的数组实现

    struct STACK {
        int top;
        Elementtype elements [maxlength];
    };
    
    void MakeNull(STACK &S)
    {
        S.top = maxlength;    
    }
    
    boolean Empty(STACK S)
    {
        if(S.top > maxlength - 1)
            return TRUE;
        else
            return FALSE;
    }
    
    Elementtype Top(STACK S)
    {
        if(Empty(S))
            return NULL;
        else
            return S.elements[S.top];
    }
    
    void Pop(STACK &S)
    {
        if(Empty(S))
            error("stack is empty");
        else
            S.top = S.top + 1;
    }
    
    void Push(Elementtype x, STACK &S)
    {
        if(S.top == 0)
            error("stack is full");
        else {
            S.top = S.top - 1;
            S.elements[S.top] = x;
        }
    }
    

3. 栈的指针实现

    struct node {
        Elementtype val;
        node *next;
    };
    
    typedef node * STACK;
    
    void MakeNull(STACK S)
    {
        S = new node;
        S->next = NULL;
    }
    
    void Push(Elementtype x, STACK S)
    {
        STACK stk;
        stk = new node;
        stk->val = x;
        stk->next = S->next;
        S->next = stk;
    }
    
    void Pop(STACK S)
    {
        STACK s;
        if(S->next)
            stk = S->next;
            S->next = stk->next;
            delete stk;
    }
    
    Elementtype Top(STACK S)
    {
        if(S->next)
            return S->next->val;
        else
            return NULL;
    }
    
    boolean Empty(STACK S)
    {
        if(S->next)
            return FALSE;
        else
            return TRUE;
    }
    

部分资料来自《数据结构与算法--张岩》

posted @ 2017-04-08 17:37  va_chester  阅读(180)  评论(0编辑  收藏  举报