代码随想录第十天| 232.用栈实现队列 |225. 用队列实现栈
因为之前比较忙期末考试=-= 所以断了打卡 现在 重新补起来~!
232.用栈实现队列
题目链接:https://leetcode.cn/problems/implement-queue-using-stacks/
看到题目的第一想法:因为一刷过,所以知道用两个栈来实现第一个栈用来存储
第二个栈就用来 将第一个栈的存储顺序变为队列的顺序
实现中遇到的困难:在实现pop的时候在想 如果转换到第二个栈之后如果还要添加怎么办
没有想到在删除之后 重新把第二个栈里面的元素放到第一个栈当中.
看到代码随想录之后的想法:进行还原 每一次要输出的时候再转化为队列(移到第二个栈当中)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | class MyQueue { stack< int > TheFirstStack; stack< int > TheSecoundStack; public : MyQueue() { } void push( int x) { TheFirstStack.push(x); } int pop() { while (!TheFirstStack.empty()) { auto tmp=TheFirstStack.top(); TheFirstStack.pop(); TheSecoundStack.push(tmp); } auto del=TheSecoundStack.top(); TheSecoundStack.pop(); while (!TheSecoundStack.empty()) { auto tmp=TheSecoundStack.top(); TheSecoundStack.pop(); TheFirstStack.push(tmp); } return del; } int peek() { while (!TheFirstStack.empty()) { auto tmp=TheFirstStack.top(); TheFirstStack.pop(); TheSecoundStack.push(tmp); } auto tmp=TheSecoundStack.top(); while (!TheSecoundStack.empty()) { auto tmp=TheSecoundStack.top(); TheSecoundStack.pop(); TheFirstStack.push(tmp); } return tmp; } bool empty() { if (TheFirstStack.empty()) { return true ; } return false ; } }; |
225. 用队列实现栈
题目链接:https://leetcode.cn/problems/implement-stack-using-queues/
看到题目的第一想法:因为一刷过.看到题目是要求使用两个队列,就想到用两个队列
实现中遇到的困难:因为做了第一个题陷入逻辑闭环,不知道怎么去实现
其实就是少循环队列大小一次,然后最后面的那个就是要移除的值.
看到代码随想录之后的想法:明白了如何实现
1 class MyStack 2 { 3 public: 4 queue<int> theFisrtQueue; 5 queue<int> theSecoundQueue; 6 MyStack() 7 { 8 } 9 10 void push(int x) 11 { 12 theFisrtQueue.push(x); 13 } 14 15 int pop() 16 { 17 int size = theFisrtQueue.size(); 18 size--; 19 while (size--) 20 { 21 auto tmp = theFisrtQueue.front(); 22 theFisrtQueue.pop(); 23 theSecoundQueue.push(tmp); 24 } 25 int result = theFisrtQueue.front(); 26 theFisrtQueue.pop(); 27 while (!theSecoundQueue.empty()) 28 { 29 auto tmp = theSecoundQueue.front(); 30 theSecoundQueue.pop(); 31 theFisrtQueue.push(tmp); 32 } 33 return result; 34 } 35 36 int top() 37 { 38 auto top=theFisrtQueue.back(); 39 return top; 40 41 } 42 43 bool empty() 44 { 45 if (theFisrtQueue.empty()) 46 { 47 return true; 48 } 49 return false; 50 } 51 };
用了不到一个小时,加油补上吧,虽然真的很累...
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端