记录LeetCode算法讲解经典版,涉及相关数据结构和算法的经典题目及相关题目解题思想和代码实现。
目录
一、预备知识
- 栈是先进后出的线性表,队列是先进先出的线性表。
- c++STL中封存了栈的数据结构stack,其中是stack的相关操作。
- c++STL中封存了栈的数据结构queue,其中是queue的相关操作。
- 二叉堆:父节点始终比子节点大的完全二叉树。
- c++STL中优先队列封存了二叉堆。
二、例题
例1、使用队列实现栈(easy)(栈、队列)
- 解题思路:申请一个临时队列,在新元素进入原始队列之前,将原始队列里的元素依次压入临时队列,新元素进入原始队列,再将临时队列里元素依次压入原始队列。
- 代码实现
#include<stdio.h>
#include<queue>
using namespace std;
class MyStack {
private:
queue<int> data;
public:
/** Initialize your data structure here. */
MyStack() {
}
/** Push element x onto stack. */
void push(int x) {
/*定义临时队列*/
queue<int> temp_data;
/*原始队列元素依次进入临时队列*/
while(!data.empty()){
int temp=data.front();
data.pop();
temp_data.push(temp);
}
/*新元素进入*/
data.push(x);
/*临时队列元素再依次进入原始队列*/
while(!temp_data.empty()){
int temp = temp_data.front();
temp_data.pop();
data.push(temp);
}
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
int temp = data.front();
data.pop();
return temp;
}
/** Get the top element. */
int top() {
return data.front();
}
/** Returns whether the stack is empty. */
bool empty() {
return data.empty();
}
};
/**
* Your MyStack object will be instantiated and called as such:
* MyStack* obj = new MyStack();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->top();
* bool param_4 = obj->empty();
*/
例2、使用栈实现队列(easy)(栈、队列)
- 解题思路:同上。
- 代码实现:
#include<stack>
using namespace std;
class MyQueue {
private:
stack<int> data