LeetCode刷题记录12——232. Implement Queue using Stacks(easy)

LeetCode刷题记录12——232. Implement Queue using Stacks(easy)

目录

LeetCode刷题记录12——232. Implement Queue using Stacks(easy)

前言

题目

语言

思路

源码

后记


前言

从今天开始学习用C++来打代码(身边的ACM大佬比赛都用C++),虽然已经学习过C和Java了,但是在写的时候,脑子里想的是面对对象,写来写去又感觉再写C一样。。。还是很不熟练,希望能边学边练。

题目

此题是关于数据结构的,关于栈和队列的操作,学过数据结构的应该都知道。题目目标是用栈来实现队列的操作。

语言

C++

思路

做这题得先理解栈和队列各自的特点,总结就是一句话:栈后进先出、队列先进先出。理解这个之后,后面就好办多了。

用两个栈来实现队列的操作。一个s1一个s2。

  1. void push(int x):实现进队操作,将x放在最后。先将栈s2中的元素全部出栈、然后进栈到s1。最后再将x元素进栈到s1,这样x就在最后面了。

  2. int pop():实现出栈操作。先将栈s1中的元素全部出栈、然后进栈到s2。这样之后,相当于把栈s1中的值逆序排放在s2中,这样再去取s2中的top,其实就是队列的头元素。

  3. int peek():返回头元素。先将栈s1中的元素全部出栈、然后进栈到s2。取s2中的top,其实就是队列的头元素。

  4. bool empty():判空。如果s1、s2中均为空,返回true,否则返回false。

源码

class MyQueue {
    stack<int>s1;
    stack<int>s2;
public:
    /** Initialize your data structure here. */
    MyQueue() {
        
    }
    
    /** Push element x to the back of queue. */
    void push(int x) {
        while (!s2.empty()) {
            s1.push(s2.top()); 
            s2.pop();
        }
        s1.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    int pop() {
        int item;
        while (!s1.empty()) {
            s2.push(s1.top()); 
            s1.pop();
        }
        s2.top();
        s2.pop();
        return item;
    }
    
    /** Get the front element. */
    int peek() {
        while (!s1.empty()) {
            s2.push(s1.top()); 
            s1.pop();
        }
        return s2.top();
    }
    
    /** Returns whether the queue is empty. */
    bool empty() {
        if(s1.empty() && s2.empty())
        return true;
    }
};
​
/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue obj = new MyQueue();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.peek();
 * bool param_4 = obj.empty();
 */

后记

做这样的栈和队列,主要抓住其各自的特点:栈后进先出、队列先进先出。最好做的时候画画示意图,就很清楚了。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值