问题
使用栈实现队列的下列操作:
push(x) — 将一个元素放入队列的尾部。
pop() — 从队列首部移除元素。
peek() — 返回队列首部的元素。
empty() — 返回队列是否为空。
MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
queue.peek(); // 返回 1
queue.pop(); // 返回 1
queue.empty(); // 返回 false
说明:
你只能使用标准的栈操作 — 也就是只有 push to top, peek/pop from top, size, 和 is empty 操作是合法的。
你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。
假设所有操作都是有效的 (例如,一个空的队列不会调用 pop 或者 peek 操作)。
Implement the following operations of a queue using stacks.
push(x) — Push element x to the back of queue.
pop() — Removes the element from in front of queue.
peek() — Get the front element.
empty() — Return whether the queue is empty.
MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
queue.peek(); // returns 1
queue.pop(); // returns 1
queue.empty(); // returns false
Notes:
You must use only standard operations of a stack — which means only push to top, peek/pop from top, size, and is empty operations are valid.
Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).
示例
public class Program { public static void Main(string[] args) { var queue = new MyQueue(); queue.Push(1); queue.Push(2); queue.Push(3); Console.WriteLine(queue.Peek()); Console.WriteLine(queue.Pop()); Console.WriteLine(queue.Empty()); Console.ReadKey(); } public class MyQueue { private Stack<int> _stack = null; public MyQueue() { _stack = new Stack<int>(); } public void Push(int x) { //基本思路是反转原栈 var stack = new Stack<int>(); stack.Push(x); var reverse = _stack.Reverse().ToList(); foreach(var elemet in reverse) { stack.Push(elemet); } _stack = stack; } public int Pop() { return _stack.Pop(); } public int Peek() { return _stack.Peek(); } public bool Empty() { return _stack.Count == 0; } } }
以上给出1种算法实现,以下是这个案例的输出结果:
1 1 False
分析:
显而易见,因为部分运行库的使用,Push 的时间复杂度应当为: ,其它方法的时间复杂度应当为:
。
本文由 .Net中文网 原创发布,欢迎大家踊跃转载。
转载请注明本文地址:https://www.byteflying.com/archives/4108。