数据结构和算法---队列&栈

队列&栈

1.队列
先入先出,入队:Enqueue 出队:Dequeue
#include

int main() {
// 1. Initialize a queue.
queue q;
// 2. Push new element.
q.push(5);
q.push(13);
q.push(8);
q.push(6);
// 3. Check if queue is empty.
if (q.empty()) {
cout << “Queue is empty!” << endl;
return 0;
}
// 4. Pop an element.
q.pop();
// 5. Get the first element.
cout << "The first element is: " << q.front() << endl;
// 6. Get the last element.
cout << "The last element is: " << q.back() << endl;
// 7. Get the size of the queue.
cout << "The size is: " << q.size() << endl;
}

2.队列和广度优先搜索
越是接近根节点的节点越早的遍历

3.栈
后入先出的数据结构,栈的实现代码:
#include

class MyStack {
private:
vector data; // store elements
public:
/** Insert an element into the stack. /
void push(int x) {
data.push_back(x);
}
/
* Checks whether the queue is empty or not. /
bool isEmpty() {
return data.empty();
}
/
* Get the top item from the queue. /
int top() {
return data.back();
}
/
* Delete an element from the queue. Return true if the operation is successful. */
bool pop() {
if (isEmpty()) {
return false;
}
data.pop_back();
return true;
}
};

int main() {
MyStack s;
s.push(1);
s.push(2);
s.push(3);
for (int i = 0; i < 4; ++i) {
if (!s.isEmpty()) {
cout << s.top() << endl;
}
cout << (s.pop() ? “true” : “false”) << endl;
}
}

4.栈和深度优先搜索
在我们到达最深的结点之后,我们只会回溯并尝试另一条路径

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值