数据结构和算法

2018-10-11  本文已影响6人  seniusen

1. 栈的特点?

class ArrayStack
{
    private:
        int *data;      // 顺序栈
        int num;        // 栈中元素个数
        int len;        // 栈的大小

    public:
        // 初始化栈,申请一个大小为 n 的数组
        ArrayStack(int n)
        {
            data = new int[n];
            num = 0;
            len = n;
        }

        bool push(int item)
        {
            // 栈空间已满,返回 false,入栈失败
            if (num == len)
            {
                return false;
            }
            // 栈空间未满,压栈,栈中元素个数加 1
            else
            {
                data[num] = item;
                num++;
                return true;
            }
        }

        int pop()
        {
            // 栈为空,返回 -1,出栈失败
            if (num == 0)
            {
                return -1;
            }
            // 栈非空,弹出栈顶元素,栈中元素个数减 1
            else
            {
                int item = data[num-1];
                num--;
                return item;
            }
        }
};
// 单向链表
struct linked_list
{
    int data;
    linked_list *next;
};

class ListStack
{
    private:
        linked_list *head;  // 链表栈的头指针
        int num;            // 栈中元素个数

    public:
        // 初始化栈,增加一个哨兵结点,方便链表操作
        ListStack()
        {
            head = new linked_list;
            head->data = -1;
            head->next = NULL;
            num = 0;
        }

        // 压栈,在哨兵结点后插入新结点
        bool push(int item)
        {
            linked_list *node = new linked_list;
            if (node)
            {
                node->data = item;
                node->next = head->next;
                head->next = node;
                num++;
                return true;
            }
            else // 内存不足,无法插入新结点,返回 false
            {
                return false;
            }
        }

        int pop()
        {
            // 栈为空,返回 -1,出栈失败
            if (num == 0)
            {
                return -1;
            }
            // 出栈,弹出哨结点后第一个结点的值,并删除结点
            else
            {
                int item = head->next->data;
                num--;
                linked_list * node = head->next;
                head->next = node->next;
                delete node;
                return item;
            }
        }
};

2. 栈的应用?

表达式求值

3. 如何实现浏览器的前进和后退功能?

我们在浏览器中访问网页时,假设依次访问了 A > B > C 页面,此时我们可以从 C 后退到 B、A,也且可以再从 A、B 前进回到 C。

参考资料-极客时间专栏《数据结构与算法之美》

获取更多精彩,请关注「seniusen」!


seniusen
上一篇 下一篇

猜你喜欢

热点阅读