剑指offer:用两个栈实现队列
题目描述:
用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead ,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead 操作返回 -1 )
解题思路:
栈的特性:先进后出,后进先出。队列特性:先进先出,后进后出;对于两个栈stack1,stack2,如果元素1与元素2按顺序入栈到stack1,则要进行元素删除操作时,如果stack2为空,则将stack1中元素出栈到stack2中,此时stack2中栈底为元素2,栈顶为元素1,利用stack2做出栈操作,出栈顺序为元素1、元素2,实现队列功能。而当stack2中非空时,执行删除操作直接按顺序弹出stack2中元素。代码如下:
C++
class CQueue
{
stack <int>stack1,stack2;
public:
CQueue()
{
while(!stack1.empty())
{
stack1.pop();
}
while(!stack2.empty())
{
stack2.pop();
}
}
void appendTail(int value)
{
stack1.push(value)
}
int deleteHead()
{
if(stack2.empty())
{
while(!stack1.empty())
{
stack2.push(stack1.top());
stack1.pop();
}
}
if(stack2.empty())
{
return -1;
}
else
{
int deleteItem=stack2.top();
stack2.pop();
return delteItem;
}
}
};
Python:
class CQueue(object):
def __init__(self):
self.stack1=[]
self.stack2=[]
def appendTail(self,value):
self.stack1.append(value)
def deleteHead(self):
if not self.stack2:
if not self.stack1:
return -1
else:
while self.stack1:
self.stack2.append(self.stack1.pop())
return self.stack2.pop()
补充:C++中关于栈的操作
建立基于数组的栈
#include<iostream>
#include<stack>
using namespace std;
int main()
{
stack<int> stack1;
for(int i=0;i<100;i++)
{
stack1.push(i);
}
while(!stack1.empty())
{
cout<<stack1.top();
stack1.pop()
}
return 0;
}
建立基于向量的栈:
#include<vector>
template<class T,int capacity=30>
class Stack
{
public:
Stack()
{
pool.reserve(capacity);
}
void clear()
{
pool.clear();
}
bool isEmpty() const
{
return pool.empty();
}
T& topEL()
{
return pool.back();
}
T pop()
{
T el=pool.back();
pool.pop_back();
return el;
}
void push(const T &el)
{
pool.push_back(el);
}
private:
vector<T> pool;
};