232. Implement Queue using Stacks
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.
Example:
MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
queue.peek(); // returns 1
queue.pop(); // returns 1
queue.empty(); // returns false
- 问题描述
创建队列,实现队列的相应操作
- 解题思路
1.使用C语言,使用构造类型定义队列:使用数组作为队列,用两个指针分别指向队头和队尾;
队列初始化,再实现对队列的相关操作。使用C语言创建队列需要自己一步步定义队列,可能
会有点繁琐,更主要的问题是如果使用顺序队列需要对数组定义一个固定的长度,只能静态分配空间。
2.使用C++,C++可以利用分装好的标准模板库(STL)中的Vector库实现队列的功能,而且能够动
态的分配空间,不用用户自定义长度大小。在这里我用的是C++解决问题。
- 代码
C++
class MyQueue {
public:
vector<int> data;
/** Initialize your data structure here. */
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
data.push_back(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
int i=data.front();
data.erase(data.begin());
return i;
}
/** Get the front element. */
int peek() {
return data.front();
}
/** Returns whether the queue is empty. */
bool empty() {
return data.empty();
}
};
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = new MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* bool param_4 = obj.empty();
*/
- 运行结果
Runtime:0ms,超过100%的人,代码效率上还是挺高的
- 总结
1.在代码速度上,总体上看C和C++程序相对于java和python等语言快,C++在很多程序设计竞赛中被使用,就是基于它的实现速度。速度的提升有两方面,一个是编程实现上;另一个是代码运行效率上;
2.之所以有两方面的优点,是因为C++有了由优于C的标准模块库(STL),该库中有了很多分装好的方法供我们使用,减少了我们对一些常用的函数的重复编写;另外C、C++相对于其他高级语言,它能跟计算机的内部系统打交道,如内存的分配等,更加接近于计算机,在编译时对代码的解析较少,因此代码运行效率更高。
3.本题目使用了STL中的Vector库,该模块是一种顺序容器,功能上和数组差不多,但是该容器的内存空间是动态的,使用时不用考虑需要分配多大的内存空间。此外,该容器能够存放各种类型的数据,该容器也提供了函数来实现对容器的数据的操作,比如存、取、删除、添加、查找等,能够操作多种数据结构和算法。