栈、队列、堆(LeetCode 课程)

本文详细介绍了如何使用栈、队列和堆来解决LeetCode中的问题,包括用队列实现栈、用栈实现队列、包含最小函数的栈、合法的出栈序列、简单计算器、求数组中的K大数以及寻找中位数等经典算法。通过实例解析,深入理解这些数据结构的操作和应用。
摘要由CSDN通过智能技术生成

预备知识
基本操作:

  • 栈(stack)LIFO(后进先出):S.top():取出栈顶;S.empty()判断栈是否为空;S.push(x)将x添加至栈;S.pop():弹出栈顶;S.size()栈存储元素的个数
  • 队列(queue)FIFO(先进先出):Q.front():返回队列头部元素;Q.back():返回队列尾部元素;Q.empty()判断栈是否为空;Q.push(x)将x添加至栈;Q.pop():弹出栈顶;Q.size()栈存储元素的个数
  • 堆(heap):标准库中的priority queue(类型)默认构造最大堆,最小堆构造std::priority queue<int, std::vector,std::greater> small_heap;最大堆构造std::priority queue<int, std::vector,std::less> big_heap;
    big_heap.empty():判断堆是否为空;big_heap.pop():弹出对顶元素(最大值);big_heap.push(x)添加元素;big_heap.top()返回堆顶元素(最大值);big_heap.size():返回堆中元素个数

一、使用队列实现栈

使用队列实现栈的下列操作:
push(x) – 元素 x 入栈
pop() – 移除栈顶元素
top() – 获取栈顶元素
empty() – 返回栈是否为空
思路
在这里插入图片描述

#include <iostream>
#include <queue> 

using namespace std;

class MyStack{
	public:
	MyStack(){
		
	}
	void push(int x){
	 	std::queue<int> temp_queue;//申请一个临时队列temp_queue 
	 	temp_queue.push(x);         //将x先push进temp_queue 
	 	while(!_data.empty())       //然后将_data中的元素放进temp_queue 
	 	{
			 temp_queue.push(_data.front());
	 	  	 _data.pop();
	 	}
	 	while(!temp_queue.empty()) //将temp_queue中的元素放进_data中,此时存在队列中的取出顺序就与栈相同了 
	 	{
   	 	    _data.push(temp_queue.front());
	 	    temp_queue.pop();
	 	}
	}
	int pop(){
		int x=_data.front();
		_data.pop();
		return x;
	}
	int top(){
		return _data.front();
	}
	bool empty(){
		return _data.empty();
	}
	private:
	std::queue<int> _data;
};

int main()
{
	MyStack S;
	S.push(1); 
	S.push(2); 
	S.push(4);
	S.push(6); 
	cout<<S.top()<<endl;
	S.pop();
	cout<<S.top()<<endl;
	if(S.empty()) 
	cout<<"This stack is empty!"<<endl;
	else
	cout<<"This stack is not empty!"<<endl;
	return 0;
}

二、使用栈实现队列

使用栈实现队列的下列操作:
push(x) – 将一个元素放入队列的尾部。
pop() – 从队列首部移除元素。
peek() – 返回队列首部的元素。
empty() – 返回队列是否为空。
思路
在这里插入图片描述

#include <iostream>
#include <stack> 

using namespace std;

class MyQueue{
	public:
	MyQueue(){
		
	}
	void push(int x){
	 	std::stack<int> temp_stack;//临时栈用来调换数据顺序 
	 	while(!_data.empty())      //将_data中的数据放入临时栈中 
	 	{
			 temp_stack.push(_data.top());
	 		 _data.pop();
	 	}
 		temp_stack.push(x);    //将x push进temp_stack 
	 	while(!temp_stack.empty())//将temp_stack放进_data
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值