• 顺序栈和链栈实现


    以前参照weiss的《数据结构与算法分析》写过两篇随笔

    栈ADT的链表实现

    栈ADT的数组实现

    因为考研的缘故,现在看了严蔚敏的《数据结构 c版》也跟着写了一遍,原理都类似

    链栈:

    /*链栈*/
    typedef status
    typedef struct node Stack;
    typedef struct node * ptrToNode; 
    
    struct node
    {
        int data;
        ptrToNode next;
    };
    
    Status initStack(Stack &S) {
        S.next = NULL;
        return OK;
    }
    
    Status getTop(Stack &S, struct node &e) {
        if(!stackEmpty(S)) return ERROR;
        e = *(S.next);
        return OK;
    }
    
    Status Push(Stack &S, int e) {
        ptrToNode tmp = (ptrToNode)malloc(sizeof(struct node));
        tmp->data = e;
        tmp->next = S.next;
        S.next = tmp;
        return OK;
    }
    
    int stackEmpty(Stack &S) {
        return (S.next == NULL);
    }
    
    Status Pop(Stack &S, int &e) {
        ptrToNode tmp = S.next;
        e = tmp->data;
        S.next = tmp->next;
        free(tmp);
        return OK;
    }
    View Code

    顺序栈:

    #define STACK_INIT_SIZE 100;
    #define INCREMENT 10;
    struct node
    {
        SElementType * next;    
    };
    //struct的申明方式
    typedef struct node SElementType;
    typedef struct {
        SElementType * base;
        SElementType * top;
        int stackSize;
    }SqStack;
    
    Status initStack(SqStack &S) {
        S.base = S.top = (SElementType *)malloc(sizeof(SElementType) * STACK_INIT_SIZE);
        if(!S.base) exit(OVERFLOW);//failed to malloc cuncu
        S.stackSize = STACK_INIT_SIZE;
    }
    
    Status getTop(SqStack &S,SElementType &e) {
        if(S.base == S.top)
            return ERROR;
        e = *(S.top-1);
        return OK;
    }
    
    Status Push(SqStack &S,SElementType e) {
        if(S.top - S.base == S.stackSize) {
            //search the result of realloc
            S.base = (SElementType *)realloc(S.base, sizeof(SElementType) * (STACK_INIT_SIZE + INCREMENT));    
            if(!S.base)    exit(OVERFLOW);
            S.top = S.base + S.stackSize;
            S.stackSize += INCREMENT; 
        }
        *S.top++ = e;
        return OK;
    }
    
    Status Pop(SqStack &S,SElementType &e) {
        if(S.base == S.top)
            return ERROR;
        S.top--;
        e = *S.top;
        return OK;
    }
    View Code

    差别:

    • 比如 initStack(Stack &S) 或者 initStack(SqStack &S) 这个操作,声明S这个结构变量就再也不是在函数内进行。返回值也不是一个指针,转而变成了Status(状态)。
    • 再比如 getTop(SqStack &S,SElementType &e) 就变成了将栈顶节点这个结构体原封不动的丢给了e,而不是只要了结构体里的data。
    • 数组做栈若栈满,严蔚敏书里用了realloc扩充了数组,weiss则无。

    相同点:

    • 在链表做栈这个地方,二者都无说判断栈满的情况。因为确实,节点你是可以任意加的,除非人为设定节点的最大个数
  • 相关阅读:
    DNS-解析、劫持、污染
    JavaScript-闭包注意事项
    Firefox-常用扩展
    Nginx-server_name匹配规则
    PHP-mysqllib和mysqlnd
    Nginx-缓冲原理及优化
    Linux-NFS原理介绍
    Linux-strace命令
    语音增强的几个基本算法
    【论文:麦克风阵列增强】Microphone Array Post-Filtering For Non-Stationary Noise Suppression
  • 原文地址:https://www.cnblogs.com/gabygoole/p/5591604.html
Copyright © 2020-2023  润新知