数据结构(五)—— 栈与队列


前言

灵魂四问:

1、C++中stack,queue 是容器么?
答:不是,而是容器适配器。

2、我们使用的stack,queue是STL(C++标准库)里面的两个数据结构,是哪个版本?
答:SGI STL。

3、我们使用的STL中stack,queue是如何实现的?
答:默认是以deque为缺省情况下的底层结构。

4、stack,queue 提供迭代器来遍历空间么?
答:不提供。

相信不仅仅是C++中有这些问题,那么大家使用其他编程语言,也可以考虑一下这四个问题,栈和队列是如何实现的。

栈与队列是我们熟悉的不能再熟悉的数据结构,但它们的底层实现,很多同学都比较模糊,这其实就是基础所在。

可以出一道面试题:栈里面的元素在内存中是连续分布的么?

这个问题有两个陷阱:

陷阱1:栈是容器适配器,底层容器使用不同的容器,导致栈内数据在内存中是不是连续分布。
陷阱2:缺省情况下,默认底层容器是deque,那么deque的在内存中的数据分布是什么样的呢? 答案是:不连续的,下文也会提到deque。

一、基础

在这里插入图片描述
栈和队列是STL(C++标准库)里面的两个数据结构。

1.1 stack

stack<int> sta;
sta.pop();
sta.push(x);
x = sta.top();

先进后出(弹夹)
栈提供 push 和 pop 等等接口,所有元素必须符合先进后出规则,所以栈不提供走访功能,也不提供迭代器(iterator)。 不像是 哈希set 或者 哈希map 提供迭代器iterator来遍历所有元素。

STL中stack往往不被归类为容器,而被归类为container adapter(容器适配器)。

栈是以底层容器完成其所有的工作,对外提供统一的接口,底层容器是可插拔的(也就是说我们可以控制使用哪种容器来实现栈的功能)。
那 STL 中栈是用什么容器实现的?从下图中可以看出,栈的内部结构,栈的底层实现可以是vector,deque,list 都是可以的, 主要就是数组和链表的底层实现。
在这里插入图片描述
我们常用的SGI STL,如果没有指定底层实现的话,默认是以deque为缺省情况下栈的底层结构。
deque是一个双向队列,只要封住一段,只开通另一端就可以实现栈的逻辑了。

我们也可以指定vector为栈的底层实现,初始化语句如下:
std::stack<int, std::vector<int> > third; // 使用vector为底层容器的栈

1.2 queue

queue<int> que;
que.pop();
que.push(x);
x = que.front();

先进先出
STL queue也不被归类为容器,而被归类为container adapter( 容器适配器)。

队列中先进先出的数据结构,同样不允许有遍历行为,不提供迭代器,SGI STL中队列一样是以deque为缺省情况下的底部结构。

也可以指定list 为起底层实现,初始化queue的语句如下:
std::queue<int, std::list<int>> third; // 定义以list为底层容器的队列

二、题

2.1 232 用栈实现队列

在这里插入图片描述
思路:
1、使用两个栈,一个stIn、一个stOut
2、只有当stOut为空的时候,再从stIn里导入数据(导入stIn全部数据)
3、peek()的实现,直接复用了pop(),功能相近的函数要抽象出来,不要大量的复制粘贴

class MyQueue {
public:
    stack<int> stIn;
    stack<int> stOut;
    /** Initialize your data structure here. */
    MyQueue() {

    }
    /** Push element x to the back of queue. */
    void push(int x) {
        stIn.push(x);
    }

    /** Removes the element from in front of queue and returns that element. */
    int pop() {
        // 只有当stOut为空的时候,再从stIn里导入数据(导入stIn全部数据)
        if (stOut.empty()) {
            // 从stIn导入数据直到stIn为空
            while(!stIn.empty()) {
                stOut.push(stIn.top());
                stIn.pop();
            }
        }
        int result = stOut.top();
        stOut.pop();
        return result;
    }

    /** Get the front element. */
    int peek() {
        int res = this->pop(); // 直接使用已有的pop函数
        stOut.push(res); // 因为pop函数弹出了元素res,所以再添加回去
        return res;
    }

    /** Returns whether the queue is empty. */
    bool empty() {
        return stIn.empty() && stOut.empty();
    }
};

2.2 225 用队列实现栈

重点思路:
使用一个que即可,每次需要pop时,把que中的尾巴移动到front即可。
在这里插入图片描述

class MyStack {
public:
    queue<int> que;
    MyStack() {

    }
    
    void push(int x) {
        que.push(x);
    }
    
    int pop() {
        for(int i = 0; i < que.size()-1; ++i){
            int temp = que.front();
            que.pop();
            que.push(temp);
        }
        int temp = que.front();
        que.pop();
        return temp;
    }
    
    int top() {
        int temp = this->pop();
        que.push(temp);
        return temp;
    }
    
    bool empty() {
        return que.empty();
    }
};

2.3 20 有效的括号

括号匹配是使用栈解决的经典问题。
注意,本题“{ ( [ ) ] }”这种用例,出现为false(虽然他的左括号能够找到相应的右括号)

bool isValid(string s) {
        if (s.size() % 2 != 0) return false; // 如果s的长度为奇数,一定不符合要求
        stack<char> st;
        for (int i = 0; i < s.size(); i++) {
            if (s[i] == '(') 
                st.push(')');
            else if (s[i] == '{') 
                st.push('}');
            else if (s[i] == '[') 
                st.push(']');
            // st中,只输入左括号对应的右括号
            
            // 如果到下面elseif说明此时s[i]为右括号
			// 此时st为空,直接false;或s[i]对不上前面的左括号,返回空
            else if (st.empty() || st.top() != s[i]) 
                return false;
            // st.top() 与 s[i]相等,栈弹出元素
            else if(st.top() == s[i])
                st.pop(); 
        }
        // 遍历完s了,检查st是否为空
        return st.empty();
}

2.4 1047 删除字符串中的所有相邻重复项

在这里插入图片描述

string removeDuplicates(string S) {
        string res;
        for(char s : S){
            if(res.empty() || res.back() != s) {
                res.push_back(s);
            }else{
                res.pop_back();
            }
        }
        return res;
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

秋雨qy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值