训练营day10

前置知识点

容器

容器是一种通用的数据结构,它可以存储不同类型的元素,可以按照一定的规则进行访问、添加、删除、查找等操作。在C++ STL中,容器包括vector、list、set、map等等。这些容器都有自己的实现方式,比如vector底层使用数组来实现,list底层使用链表来实现。

容器适配器

容器适配器是一种特殊的容器,它是通过包装一个已有的容器来实现的。容器适配器提供了一种特定的接口,使得底层的容器具有了新的功能。在C++ STL中,容器适配器包括stack、queue、priority_queue等等。比如,stack是基于deque或list实现的,它提供了后进先出(LIFO)的数据存储方式。

stack和queue都是容器适配器

容器和容器适配器的区别

容器适配器和容器的区别在于,容器适配器是通过包装已有的容器来实现的,而容器则是自己独立实现的。容器适配器的接口通常比容器更加特定,用于实现一些特殊的数据结构,比如队列、栈、优先队列等。

栈与队列

相关知识点

栈-后进先出;队列-先进先出

结构:顺序存储-链式存储

对比数组和链表:简化程序设计的过程

主要应用:后缀表达式

栈-stack-常用操作

stack<int> q; //以int型为例

int x;

q.push(x); //将x压入栈顶

q.top(); //返回栈顶的元素

q.pop(); //删除栈顶的元素

q.size(); //返回栈中元素的个数

q.empty(); //检查栈是否为空,

//若为空返回true,否则返回false

队列-Queue-常用操作

q.empty() //如果队列为空返回true,否则返回false

q.size() //返回队列中元素的个数

q.pop() //删除队列首元素但不返回其值

q.front() //返回队首元素的值,但不删除该元素

q.push() //在队尾压入新元素

q.back() //返回队列尾元素的值,但不删除该元素

栈实现队列分析

class MyQueue {

public:

//创建两个栈

stack<int> stIn;

stack<int> stOut;

/** Initialize your data structure here. */

//

MyQueue() {

}

/** Push element x to the back of queue. */

//输入

//往指定的栈(stTn)进行输入

void push(int x) {

stIn.push(x);

}

//删除队列首元素且返回其值

//将in中的元素放入out中,输出out中的top元素

/** Removes the element from in front of queue and returns that element. */

int pop() {

//只有当stOut为空的时候,再从stIn里导入数据(导入stIn全部数据)

//此if环节保证out中有全部的数据,没有导入新数据则不进入这一步

if (stOut.empty()) {

// 从stIn导入数据直到stIn为空

while(!stIn.empty()) {

stOut.push(stIn.top());

stIn.pop();

}

}

//确定返回值后删除元素

int result = stOut.top();

stOut.pop();

return result;

}

/** Get the front element. */

//

int peek() {

//为了保护被弹出的数据所以有res变量

int res = this->pop(); // 直接使用已有的pop函数

stOut.push(res); // 因为pop函数弹出了元素res,所以再添加回去

return res;

}

/** Returns whether the queue is empty. */

bool empty() {

//检查in和out是否为空

return stIn.empty() && stOut.empty();

}

};

问:每次添加的时候为什么不把out返回in

答:在取数据的时候已经解决,只有当out空的时候才把in的数据放入out中

问:peek()中的this指代的是什么

答:引用了上述已经写好的pop函数

队列实现栈分析

题目链接:225. 用队列实现栈

独立实现

class MyStack {

public:

queue<int> p;

MyStack() {

}

void push(int x) {

p.push(x);

}

int pop() {

for(int i = 1;i < p.size();i++){

p.push(p.front());

p.pop();

}

int res = p.front();

p.pop();

return res;

}

int top() {

for(int i = 1;i < p.size();i++){

p.push(p.front());

p.pop();

}

int res = p.front();

p.push(p.front());

p.pop();

return res;

}

bool empty() {

return p.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();

*/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值