- 力扣top100中的数据结构类题其实不多,这里就大概写几道
实现 Trie (前缀树)
- 结构体和类不同时出现,曾经写c语言的时候或许学过结构体,但是c++类与对象之后就不会出现struct了!
- 一个class相当于一个struct
- 需要的变量都写在private里面(是自己这个对象可以直接取到的)
- Trie数节点不需要val,每个点都连着26个next(数组),建立了该节点就是存在
- 其他内容写在注释里
class Trie {
private:
bool isEnd;
Trie* next[26];
public:
Trie() {
isEnd = false;
//初始化当前节点的两个属性
memset(next, 0, sizeof(next));
}
void insert(string word) {
//取当前对象(我自己)
Trie* node = this;
//直接让头结点为空,不做任何处理
for (char c : word) {
if (node->next[c-'a'] == NULL) {
//如果该点不存在,就建立该点
node->next[c-'a'] = new Trie();
}
//相当于链表里的p=p->next;
node = node->next[c-'a'];
}
//最后的这个点的isEnd赋好值
node->isEnd = true;
}
bool search(string word) {
//取当前对象(我自己)
Trie* node = this;
for (char c : word) {
node = node->next[c - 'a'];
//如果找的next是空
if (node == NULL) {
return false;
}
}
//如果成功找到,看下是否为前缀
return node->isEnd;
}
bool startsWith(string prefix) {
Trie* node = this;
for (char c : prefix) {
node = node->next[c-'a'];
if (node == NULL) {
return false;
}
}
return true;
}
};
用栈来实现队列
- 用两个栈来实现队列!
- 也就是一个栈用来push,另一个栈pop栈,把push栈里的内容全都push进入pop栈,实现把逆序回归顺序!
class MyQueue {
private:
// 两个栈:用于实现队列的入队和出队操作
stack<int> push_stack; // 用于存储入队的元素
stack<int> pop_stack; // 用于存储反转后的元素,模拟队列的出队顺序
// 辅助函数:当 pop_stack 为空时,将 push_stack 中的元素全部转移到 pop_stack
// 这样可以模拟队列的 FIFO(先进先出)行为
void canWe() {
// 当 pop_stack 为空时,将 push_stack 中的元素转移到 pop_stack
if (pop_stack.empty()) {
// 将 push_stack 中的所有元素逐个弹出,压入 pop_stack
while (!push_stack.empty()) {
pop_stack.push(push_stack.top()); // 将 push_stack 顶部元素压入 pop_stack
push_stack.pop(); // 弹出 push_stack 顶部元素
}
}
}
public:
// 构造函数:初始化队列对象
MyQueue() {}
// 入队操作:将元素压入 push_stack
void push(int x) {
push_stack.push(x); // 将新元素 x 压入 push_stack
}
// 出队操作:从队列前端移除并返回元素
int pop() {
canWe(); // 确保 pop_stack 中有元素可供出队
int x = pop_stack.top(); // 获取队列前端的元素(位于 pop_stack 顶部)
pop_stack.pop(); // 从 pop_stack 中移除该元素
return x; // 返回出队的元素
}
// 获取队列前端的元素,但不移除它
int peek() {
canWe(); // 确保 pop_stack 中有元素可以查看
return pop_stack.top(); // 返回队列前端的元素(位于 pop_stack 顶部)
}
// 判断队列是否为空
bool empty() {
// 当 push_stack 和 pop_stack 都为空时,队列为空
return push_stack.empty() && pop_stack.empty();
}
};
/**
* 说明:
* MyQueue* obj = new MyQueue(); // 创建一个 MyQueue 对象
* obj->push(x); // 将元素 x 入队
* int param_2 = obj->pop(); // 出队操作,返回并移除队列前端的元素
* int param_3 = obj->peek(); // 获取队列前端的元素,但不移除它
* bool param_4 = obj->empty(); // 检查队列是否为空
*/
*/
用队列实现栈
- 用一个队列来实现,而非和上题一样用两个队列(因为多少个队列都没用,永远是先进先出的“顺序”)
- 必须用下面push展示的逻辑来实现先进后出!
class MyStack {
public:
MyStack() {
// 构造函数可以是空的
}
void push(int x) {
q.push(x);
int s = q.size();
while (s > 1) {
q.push(q.front());
q.pop();
s--;
}
}
int pop() {
int x = q.front();
q.pop();
return x;
}
int top() { return q.front(); }
bool empty() { return q.empty(); }
private:
queue<int> q;
};
/**
* 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();
*/