用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead ,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead 操作返回 -1 )
题解:
1.两个栈实现一个队列
2.队列尾部插入整数appendTail
3.队列头部删除整数 deleteHead
4.删除时没有元素返回-1
示例 1:
输入:
["CQueue","appendTail","deleteHead","deleteHead"]
[[],[3],[],[]]
输出:[null,null,3,-1]
示例 2:
输入:
["CQueue","deleteHead","appendTail","appendTail","deleteHead","deleteHead"]
[[],[],[5],[2],[],[]]
输出:[null,-1,null,null,5,2]
提示:
1 <= values <= 10000
最多会对 appendTail、deleteHead 进行 10000 次调用
解题思路:
两个栈模拟队列分别负责插入和删除功能
初始化两个栈
插入栈不断push插入,再删除时考虑删除操作的逻辑
第二栈负责删除栈顶(队头),所以删除栈本身有元素,返回栈顶元素,后序有删除操作,等删除栈里元素删除完,再添加新元素
为实现队列的先进先出,从插入栈从顶到底压入删除栈,这样栈顶即队头
如果一开始没插入元素,这样删除栈也为空,删除操作返回-1
如果删除栈一开始为空,插入栈有元素,添加后删除栈有元素了,则返回栈顶。
C/C++题解:
class CQueue {
public:
stack<int> fir,sec;
CQueue() {}
void appendTail(int value) {
fir.push(value);}//插入栈只插入
int deleteHead() {//删除时
if(!sec.empty()){//如果删除栈里不空
int res = sec.top();
sec.pop();//直接返回栈顶
return res;//插入栈不做处理
//直到删除栈里元素没了在从插入栈往删除栈加
}//把插入栈里的元素压入删除栈
while(!fir.empty()){
int ele = fir.top();
fir.pop();
sec.push(ele);}//删除栈里空,返回-1
if(sec.empty()) return -1;
//非空,返回栈顶元素
int res = sec.top();
sec.pop();
return res;}};
/** * Your CQueue object will be instantiated and called as such:
* CQueue* obj = new CQueue();
* obj->appendTail(value);
* int param_2 = obj->deleteHead(); */
Debug结果:
Java题解:
class CQueue {
public LinkedList<Integer> fir,sec;
public CQueue() {
fir = new LinkedList<Integer>();
sec = new LinkedList<Integer>();}
public void appendTail(int value) { fir.push(value);}
public int deleteHead() {//删除时
if(!sec.isEmpty()){//如果删除栈里不空
int res = sec.pop();//直接返回栈顶
return res;//插入栈不做处理
//直到删除栈里元素没了在从插入栈往删除栈加
}//把插入栈里的元素压入删除栈
while(!fir.isEmpty()){
int ele = fir.pop();
sec.push(ele); }//删除栈里空,返回-1
if(sec.isEmpty()) return -1;
//非空,返回栈顶元素
int res = sec.pop();
return res;}}
/** * Your CQueue object will be instantiated and called as such:
* CQueue obj = new CQueue();
* obj.appendTail(value);
* int param_2 = obj.deleteHead();*/
Debug结果:
Python题解:
class CQueue(object):
def __init__(self):
self.fir, self.sec = [], []
def appendTail(self, value):
""":type value: int:rtype: None"""
self.fir.append(value)
def deleteHead(self):
""":rtype: int"""
if self.sec: #如果删除栈里不空
res = self.sec.pop() #直接返回栈顶
return res#插入栈不做处理
#直到删除栈里元素没了在从插入栈往删除栈加
#把插入栈里的元素压入删除栈
while self.fir:
ele = self.fir.pop()
self.sec.append(ele)
#删除栈里空,返回-1
if not self.sec: return -1
#非空,返回栈顶元素
res = self.sec.pop()
return res
# while self.first:
# self.second.append(self.first.pop())
# if not self.second:
# return -1;
# res = self.second.pop()
# while self.second:
# self.first.append(self.second.pop())
# return res
# list优势
# if not self.first:
# return -1;
# return self.first.pop(0)
# Your CQueue object will be instantiated and called as such:
# obj = CQueue()
# obj.appendTail(value)
# param_2 = obj.deleteHead()
Debug结果:
更多题解移步公众号免费获取