最近在刷算法题,发表出来与大家分享,有错误还望指出,
本博客目录
- 实现返回最小元素功能的栈结构
- 用队列实现栈结构
- 用栈实现队列结构
实现一个特殊的栈
在实现栈功能的基础上,在返回实现栈中最小元素的操作
要求:
- pop,push,getMin操作时间复杂度为O(1)
- 可以使用现成的栈结构
用两个栈来实现,栈1正常存储,来一个数压栈一个。栈2实现最小元素,当新来的数比栈顶元素小时,压入新来的,大于栈顶元素时,重复压入栈顶元素。
#include <iostream> #include <stack> using namespace std; class getminStack { public: getminStack(); ~getminStack(); void push(int num); int pop(); int top(); int getmin(); private: stack<int> stack1; stack<int> stack2; };
#include "getminStack.h" getminStack::getminStack() { } getminStack::~getminStack() { } void getminStack::push(int num) { stack1.push(num); if (stack2.empty()) { stack2.push(num); } else { if (num < stack2.top()) { stack2.push(num); } else { stack2.push(stack2.top()); } } } int getminStack::top() { return stack1.top(); } int getminStack::pop() { int i = stack1.top(); stack2.pop(); stack1.pop(); return i; } int getminStack::getmin() { if (stack2.empty) { cout << "Error, the stack is empty!" << endl; } return stack2.top(); }
用队列实现栈结构
用两个队列实现一个栈,当需要压入数时,往一个固定的队列1中压入,需要弹出时,将队列1中的数弹出压入队列2,直到只剩下一个数为止,将最后一个数弹出,实现栈的弹出操作,将队列1和队列2交换,以便下次在往队列1中压入元素。
#include<queue> #include<stack> #include<iostream> using namespace std; class queueToStack { public: queueToStack(); ~queueToStack(); void push(int num); int pop(); int top(); void swap(); private: queue<int> mainQueue; queue<int> help; };
#include "queueToStack.h" queueToStack::queueToStack() { } queueToStack::~queueToStack() { } void queueToStack::swap() { queue<int> tmp; tmp = mainQueue; mainQueue = help; help = tmp; } void queueToStack::push(int num) { mainQueue.push(num); } int queueToStack::pop() { if (mainQueue.empty()) { cout << "Error, the stack has no number!" << endl; return 0; } while (mainQueue.size() > 1){ help.push(mainQueue.front()); mainQueue.pop(); } int tmp = mainQueue.front(); mainQueue.pop(); swap(); return tmp; } int queueToStack::top() { if (mainQueue.empty()) { cout << "Error, the stack is empty" << endl; return 0; } while (mainQueue.size() != 1){ help.push(mainQueue.front()); mainQueue.pop(); } int tmp = mainQueue.front(); help.push(tmp); mainQueue.pop(); swap(); return tmp; }
用栈实现队列操作
#include<iostream> #include<stack> using namespace std; class stackToQueue { public: stackToQueue(); ~stackToQueue(); void push(int num); int pop(); int top(); private: stack<int> stack1; stack<int> stack2; };
#include "stackToQueue.h" stackToQueue::stackToQueue() { } stackToQueue::~stackToQueue() { } void stackToQueue::push(int num) { stack1.push(num); } int stackToQueue::pop() { if (stack1.empty() && stack2.empty()) { cout << "Error, the queue is empty!" << endl; return 0; } else if (stack2.empty()) { while (!stack1.empty()) { stack2.push(stack1.top()); stack1.pop(); } } int tmp = stack2.top(); stack2.pop(); return tmp; } int stackToQueue::top() { if (stack1.empty() && stack2.empty()) { cout << "Error, the queue is empty!" << endl; return 0; } else if (stack2.empty()) { while (!stack1.empty()) { stack2.push(stack1.top()); stack1.pop(); } } return stack2.top(); }