您的位置:首页 > 其它

堆栈的一些小小的实践

2015-08-03 05:58 330 查看
/*只用一个数组实现三个栈*/
/*方法1,每个栈都有一个栈顶,三部分平分数组*/
#define SIZE 100
template<class T> class istack{
private:
int size;
T *buf;
int stack_top[3];
public:
istack(int i = 300){
size = i;
buf = new  T[i * 3];
stack_top[0] = stack_top[1] = stack_top[2] = -1;
}
~istack(){
delete[]  buf;
}
void push(int stack_num, T n){
int pos = stack_num*size + stack_top[stack_num] + 1;
buf[pos] = n;
stack_top[stack_num]++;
}

T pop(int stack_num){
if (empty(stack_num))
return NULL;
stack_top[stack_num]--;

int pos = stack_num*size + stack_top[stack_num]+1;
return buf[pos];
}
int top(int stack_num){
return stack_top[stack_num]+stack_num*size;
}
bool empty(int stack_num){
return stack_top[stack_num] == -1;
}
};
/*实现一个栈,除了push和pop操作,还要实现min函数以返回栈中的最小值。 push,pop和min函数的时间复杂度都为O(1)。*/
/*push的时候可以用一个变量来保存当前最小值,但是在pop时就比较麻烦,因为不知道pop之后的最小值*/
/*可以每一个结点中都push了这个结点时的最小值*/
/*但是这存在一个问题,有可能有数据冗余,多个结点的最小值都是相等的.
更好的解决办法是使用另一个小堆栈来存储最小值,每一次pop时都会与当前值进行比较*/
template<class T>class stack{
private:T* buf;
int cur;
public:
stack(int size=100){
cur = -1;
buf = new T[size];
}
~stack(){
delete[] buf;
}
void push(T number){
buf[++cur] = number;
}
T pop(){
return buf[cur--];
}
bool empty(){
return cur == -1;
}
T top(){
return buf[cur];
}
};
class minstack{
private:
stack<int> s, min;
public :
void push(int num){
s.push(num);
if (!(num > min.top()))
min.push(num);
}
int pop(){
if (s.top() == min.top())
min.pop();
return s.pop();
}
bool empty(){
return s.empty();
}
int min(){
if (min.empty())
return INT_MAX;
return min.top();
}
};
/*使用两个栈实现一个队列MyQueue。*/
/*思路是入队列时压入到A栈中,出队列时将B中的出栈,如果B为空,则将A出栈,压入B*/
template <class T>class queue_stack{
private:
stack<T> src, dst;
public:
void push(T val){
src.push(val);
}
T pop(){
if (dst.empty()){
while (src.empty()){
dst.push(src.pop());
}
}
return dst.pop();
}

};

/*写程序将一个栈按升序排序。对这个栈是如何实现的,你不应该做任何特殊的假设。 程序中能用到的栈操作有:push | pop | peek | isEmpty。*/
stack<int> Ssort(stack<int> s){
stack<int> t;
while (!s.empty()){
int data = s.top();
s.pop();
while (!t.empty() && t.top()>data){
s.push(t.top());
t.pop();
}
t.push(data);
}
return t;
}
/*方案2:

使用一个优先队列来为出栈的元素排序,原栈中的元素不断出栈然后插入优先队列, 直到原栈为空。然后再将优先队列中的元素不断压回原栈,这样操作后, 栈中的元素便有序化了。

代码如下:
*/
#include <cstdlib>
#include <stack>
#include <queue>
#include<functional>
using namespace std;
void Qsort(stack<int> &s){
priority_queue< int, vector<int>, greater<int> > q;
while (!s.empty()){
q.push(s.top());
s.pop();
}
while (!q.empty()){
s.push(q.top());
q.pop();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: