題目描述
使用棧實現(xiàn)隊列的下列操作:
push(x) -- 將一個元素放入隊列的尾部笋敞。
pop() -- 從隊列首部移除元素。
peek() -- 返回隊列首部的元素荠瘪。
empty() -- 返回隊列是否為空夯巷。
棧:先進后出;
隊列:先進先出哀墓;
思路:
1.使用兩個棧stack 趁餐、queue ;
2.將數(shù)據(jù)push到stack中;
3.queue 進行出隊,則是stack中出棧篮绰,如果queue無數(shù)據(jù)則stack就行出棧后雷,如果queue 有數(shù)據(jù)就進行出棧;
Stack<int> stack = new Stack<int>();
Stack<int> queue = new Stack<int>();
public MyQueue()
{
}
public void Push(int x)
{
stack.push(x);
}
public int Pop()
{
if (queue.isEmpty())
{
while (stack.top != null)
{
queue.push(stack.peek());
stack.pop();
}
}
int topV = queue.peek();
queue.pop();
return topV;
}
/** Get the front element. */
public int Peek()
{
if (queue.isEmpty())
{
while (stack.top != null)
{
queue.push(stack.peek());
stack.pop();
}
}
return queue.peek();
}
/** Returns whether the queue is empty. */
public bool Empty()
{
if (queue.isEmpty())
{
while (stack.top != null)
{
queue.push(stack.peek());
stack.pop();
}
}
if (queue.top == null) return false;
return true;
}