首页 > 其他 > 详细

栈的指针写法

时间:2020-11-14 17:31:53      阅读:23      评论:0      收藏:0      [点我收藏+]
#include <cstdio>

struct Stack {

    struct node {
        node* below;        // 这个元素的下面那个元素
        int key;            // 这个元素的值
    } *nowTop;

    void push(int x) {      // 向栈顶压入一个数
        node* todo = new node();
        todo->below = nowTop;
        todo->key = x;

        nowTop = todo;
    }

    void pop() {            // 弹出栈顶
        node *old = nowTop;
        nowTop = old->below;
        delete old;
    }

    int top() {             // 返回栈顶的值
        return nowTop->key;
    }
};

Stack s;

int main(void) {
    s.push(1);
    s.push(2);

    printf("%d\n", s.top());

    s.pop();
    printf("%d\n", s.top());

    s.push(3);
    s.push(4);

    printf("%d\n", s.top());

    s.pop();

    printf("%d\n", s.top());


    s.pop();

    s.push(5);

    printf("%d\n", s.top());

    s.pop();

    printf("%d\n", s.top());


    s.pop();


    return 0;
}

栈的指针写法

原文:https://www.cnblogs.com/SeekHummingbird/p/13973381.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!