移情别恋c++ ദ്ദി˶ー̀֊ー́ ) ——8.stackqueue

2024-08-27 14:12
文章标签 c++ stackqueue 移情别恋

本文主要是介绍移情别恋c++ ദ്ദി˶ー̀֊ー́ ) ——8.stackqueue,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1.用栈实现队列

. - 力扣(LeetCode)

思路

1.将一个栈当作输入栈,用于压入 push 传入的数据;另一个栈当作输出栈,用于 pop 和 peek 操作。

2.每次 pop 或 peek 时,若输出栈为空将输入栈的全部数据依次弹出并压入输出栈,这样输出栈从栈顶往栈底的顺序就是队列从队首往队尾的顺序。

class MyQueue {
private:stack<int> inStack, outStack;void in2out() {while (!inStack.empty()) {outStack.push(inStack.top());inStack.pop();}}public:MyQueue() {}void push(int x) {inStack.push(x);}int pop() {if (outStack.empty()) {in2out();}int x = outStack.top();outStack.pop();return x;}int peek() {if (outStack.empty()) {in2out();}return outStack.top();}bool empty() {return inStack.empty() && outStack.empty();}
};

2. 用队列实现栈

 

class MyStack {
public:queue<int> queue1;queue<int> queue2;/** Initialize your data structure here. */MyStack() {}/** Push element x onto stack. */void push(int x) {queue2.push(x);while (!queue1.empty()) {queue2.push(queue1.front());queue1.pop();}swap(queue1, queue2);}/** Removes the element on top of the stack and returns that element. */int pop() {int r = queue1.front();queue1.pop();return r;}/** Get the top element. */int top() {int r = queue1.front();return r;}/** Returns whether the stack is empty. */bool empty() {return queue1.empty();}
};

3.数组中的第k个最大元素 

 思路:

1.先取数组的前k个元素,使用向上调整算法建立小堆(a[0]为最小值)

2.再遍历剩余数组,如果元素大于a[0],则替代a[0]入堆并使用向下调整算法调整

3.返回a[0];

 

typedef struct heap
{int* a;int size;int capacity;
}HP;void swap(int* p1, int* p2)
{int t = 0;t = *p1;*p1 = *p2;*p2 = t;
}void heapinit(HP* php)
{assert(php);php->a = NULL;php->size = 0;php->capacity = 0;
}void adjustup(int* a, int child)         //向上调整法          //上方必须是堆
{int parent = (child-1)/2;while (child>0){if (a[parent]>=a[child])        //小堆为>=,大堆为<={swap(&a[parent],&a[child]);child = parent;parent = (child - 1)/2;}else{break;}}
}void adjustdown(int* a,int n, int parent)     //向下调整法,!!!!!!(仅适用于根结点两端都是大堆或小堆)
{int child = 2 * parent + 1;while (child<=n)                   //{if (child + 1<=n && a[child + 1] < a[child])      //   child+1>n可以推出child==n,所以只有左孩子{child++;                          //选出左右孩子中最大的一个‘>’,最小的为'<'}if (a[parent]>=a[child])        //大堆为“<=”,小堆为“>=”{swap(&a[parent], &a[child]);parent = child;child = 2 * parent + 1;     //每次都先找左孩子}else{break;}}
}void heappush(HP* php, int data)
{php->a[php->size] = data;php->size++;adjustup(php->a, php->size - 1);
}int findKthLargest(int* nums, int numsSize, int k) {HP sl;heapinit(&sl);sl.a=(int*)malloc(sizeof(int)*k);int i=0;for(i=0;i<k;i++)heappush(&sl, nums[i]);for(i=k;i<numsSize;i++){if(nums[i]>sl.a[0]){sl.a[0]=nums[i];adjustdown(sl.a,k-1,0);  //记得是k-1}}return sl.a[0];
}

4.最小栈 

 

class MinStack {
public:
public:void push(int x) {// 只要是压栈,先将元素保存到_elem中_elem.push(x);// 如果x小于_min中栈顶的元素,将x再压入_min中!!!!!!!!!!if (_min.empty() || x <= _min.top())_min.push(x);}void pop() {// 如果_min栈顶的元素等于出栈的元素,_min顶的元素要移除!!!!!!!!if (_min.top() == _elem.top())_min.pop();_elem.pop();}int top() { return _elem.top();}int getMin() { return _min.top(); }private:// 保存栈中的元素std::stack<int> _elem;// 保存栈的最小值std::stack<int> _min;
};

 

5.栈的弹出压入序列 

1.设置flag,i,i用来遍历pushv数组;

2.当arr.top()==popV[flag]时,arr.pop(),flag++,

3.当pushV[i]==popV[flag]时,flag++;

4.遍历完成后,

for(;flag<popV.size();flag++)

          {

            if(popV[flag]!=arr.top())

            return false;

            else

             {

                arr.pop();

             }

          }

5.return true

class Solution {
public:bool IsPopOrder(vector<int>& pushV, vector<int>& popV) {int flag=0;for(int i=0;i<pushV.size();i++){if(pushV[i]!=popV[flag]){if(!arr.empty()){if(arr.top()==popV[flag]){arr.pop();flag++;while(!(arr.empty())&&arr.top()==popV[flag]) 
//如果连续遇到arr.top()==popV[flag],则一直arr.pop();flag++,直至两者不同{arr.pop();flag++;}arr.push(pushV[i]);}else {arr.push(pushV[i]);}}elsearr.push(pushV[i]);}else{flag++;}}for(;flag<popV.size();flag++){if(popV[flag]!=arr.top())return false;else{arr.pop();}}return true;}private:stack<int> arr;
};

 

6.逆波兰表达式求值 

1.设置两个stack,一个存数字(arr),一个存符号(brr)

2.遍历数组,若为数字则 入栈arr;

3.若为符号,则入栈brr,并取brr.top,arr.top(两次)

进行operation,并把返回值压入arr栈中;

4.返回arr.top;

class Solution {
public:int operation(int a, int b, string s) {if (s[0] == '+')return b + a;        //记得是b在前,a在后,因为栈是后进先出if (s[0] == '-')return b - a;if (s[0] == '*')return b * a;if (s[0] == '/')return b / a;return 1; // 记得写一个return// 1,因为系统判定如果if都不走,那么就没有返回值}int evalRPN(vector<string>& tokens) {int num = 0;int result = 0;string j;int a;int b;int end;for (int i = 0; i < tokens.size(); i++) {if (tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "*" ||tokens[i] == "/") {brr.push(tokens[i]);a = arr.top();arr.pop();b = arr.top();arr.pop();end = operation(a, b, brr.top());arr.push(end);brr.pop();} else {j = tokens[i];if (j[0] == '-') {for (int i = 1; i < j.size(); i++) {num = num * 10 + (j[i] - '0');}arr.push(-num);num = 0;} else {for (int i = 0; i < j.size(); i++) {num = num * 10 + (j[i] - '0');}arr.push(num);num = 0;}}}end = arr.top();return end;}private:stack<int> arr;stack<string> brr;
};

 

这篇关于移情别恋c++ ദ്ദി˶ー̀֊ー́ ) ——8.stackqueue的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1111894

相关文章

C++右移运算符的一个小坑及解决

《C++右移运算符的一个小坑及解决》文章指出右移运算符处理负数时左侧补1导致死循环,与除法行为不同,强调需注意补码机制以正确统计二进制1的个数... 目录我遇到了这么一个www.chinasem.cn函数由此可以看到也很好理解总结我遇到了这么一个函数template<typename T>unsigned

C++统计函数执行时间的最佳实践

《C++统计函数执行时间的最佳实践》在软件开发过程中,性能分析是优化程序的重要环节,了解函数的执行时间分布对于识别性能瓶颈至关重要,本文将分享一个C++函数执行时间统计工具,希望对大家有所帮助... 目录前言工具特性核心设计1. 数据结构设计2. 单例模式管理器3. RAII自动计时使用方法基本用法高级用法

深入解析C++ 中std::map内存管理

《深入解析C++中std::map内存管理》文章详解C++std::map内存管理,指出clear()仅删除元素可能不释放底层内存,建议用swap()与空map交换以彻底释放,针对指针类型需手动de... 目录1️、基本清空std::map2️、使用 swap 彻底释放内存3️、map 中存储指针类型的对象

C++ STL-string类底层实现过程

《C++STL-string类底层实现过程》本文实现了一个简易的string类,涵盖动态数组存储、深拷贝机制、迭代器支持、容量调整、字符串修改、运算符重载等功能,模拟标准string核心特性,重点强... 目录实现框架一、默认成员函数1.默认构造函数2.构造函数3.拷贝构造函数(重点)4.赋值运算符重载函数

C++ vector越界问题的完整解决方案

《C++vector越界问题的完整解决方案》在C++开发中,std::vector作为最常用的动态数组容器,其便捷性与性能优势使其成为处理可变长度数据的首选,然而,数组越界访问始终是威胁程序稳定性的... 目录引言一、vector越界的底层原理与危害1.1 越界访问的本质原因1.2 越界访问的实际危害二、基

c++日志库log4cplus快速入门小结

《c++日志库log4cplus快速入门小结》文章浏览阅读1.1w次,点赞9次,收藏44次。本文介绍Log4cplus,一种适用于C++的线程安全日志记录API,提供灵活的日志管理和配置控制。文章涵盖... 目录简介日志等级配置文件使用关于初始化使用示例总结参考资料简介log4j 用于Java,log4c

C++归并排序代码实现示例代码

《C++归并排序代码实现示例代码》归并排序将待排序数组分成两个子数组,分别对这两个子数组进行排序,然后将排序好的子数组合并,得到排序后的数组,:本文主要介绍C++归并排序代码实现的相关资料,需要的... 目录1 算法核心思想2 代码实现3 算法时间复杂度1 算法核心思想归并排序是一种高效的排序方式,需要用

C++11范围for初始化列表auto decltype详解

《C++11范围for初始化列表autodecltype详解》C++11引入auto类型推导、decltype类型推断、统一列表初始化、范围for循环及智能指针,提升代码简洁性、类型安全与资源管理效... 目录C++11新特性1. 自动类型推导auto1.1 基本语法2. decltype3. 列表初始化3

C++11右值引用与Lambda表达式的使用

《C++11右值引用与Lambda表达式的使用》C++11引入右值引用,实现移动语义提升性能,支持资源转移与完美转发;同时引入Lambda表达式,简化匿名函数定义,通过捕获列表和参数列表灵活处理变量... 目录C++11新特性右值引用和移动语义左值 / 右值常见的左值和右值移动语义移动构造函数移动复制运算符

C++中detach的作用、使用场景及注意事项

《C++中detach的作用、使用场景及注意事项》关于C++中的detach,它主要涉及多线程编程中的线程管理,理解detach的作用、使用场景以及注意事项,对于写出高效、安全的多线程程序至关重要,下... 目录一、什么是join()?它的作用是什么?类比一下:二、join()的作用总结三、join()怎么