Day10.(Day9先鸽为敬)力扣我 232.225

首先了解栈和队列

什么是栈?(水级理解!
在这里插入图片描述
什么是队列 灌水理解
在这里插入图片描述

232.用栈实现队列

依据栈实现队列的几个函数!
(可以使用栈中的函数!)

代码入下

先定义两个栈实现队列

	stack<int> sin;
    stack<int> sout;

void push(int x) 将元素 x 推到队列的末尾

void push(int x) {
        sin.push(x);//栈的push实现队列push
    }

int pop() 从队列的开头移除并返回元素

 int pop() {
         if(sout.empty())
         {
             while( sin.empty() == NULL)//empty判断空为1,不是空为0!直到sin为空!!
                {
                 sout.push(sin.top());
                 sin.pop();
                }
         }
         int temp=sout.top();
                sout.pop();
                return temp;
        
    }

int peek() 返回队列开头的元素

 int peek() {
        int a=this->pop();//两个栈实现队列!!不能直接top
        sout.push(a);
        return a;
    }

boolean empty() 如果队列为空,返回 true ;否则,返回 false

bool empty() {
        return sin.empty()&&sout.empty();//两个栈实现队列!判断两个栈
    }

完整代码

class MyQueue {
public:
    stack<int> sin;
    stack<int> sout;
    MyQueue() {

    }
    
    void push(int x) {
        sin.push(x);
    }
    
    int pop() {
         if(sout.empty())
         {
             while( sin.empty() == NULL)//直到sin为空!!
                {
                 sout.push(sin.top());
                 sin.pop();
                }
         }
         int temp = sout.top();
                sout.pop();
                return temp;
        
    }
    
    int peek() {
        int a=this->pop();//两个栈实现队列!!
        sout.push(a);
        return a;
    }
    
    bool empty() {
        return sin.empty()&&sout.empty();
    }
};

225.用队列实现栈

参照栈实现队列

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

    }
    
    void push(int x) {
        duilie.push(x);
    }
    
    int pop() {
        int n=duilie.size()-1;
        while(n--)
        {
            duilie.push(duilie.front());
            duilie.pop();
        }
        int temp=duilie.front();
        duilie.pop();
        return temp;
    }
    
    int top() {
        return duilie.back();// int a=this->pop();
      						//  duilie.push(a);
        					//		return a;
    }
    
    bool empty() {
        return duilie.empty();
    }
};

我是小白,但我要成为小亮(光头了自会反光)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值