/*双端队列可以用于存储两个栈,使用deque来实现的
*读入20个随机整数,把偶数压入一个栈
*把奇数压入另一个栈
*然后分别弹出并输出两个栈的元素,直到为空*/
//备注:随机数要加上种子,要不然不会变的,这个不是mfc版
#include<iostream>
#include <deque>
#include "time.h"
using namespace std;
enum stackNumber {one ,two};
template <typename T>
class dualStack{
public:
dualStack();//构造函数
void push(const T& item, stackNumber n);
void pop(stackNumber n);
T&top(stackNumber n);
const T&top(stackNumber n) const;
bool empty(stackNumber n) const;
int size(stackNumber n) const;
private:
deque<T>dualStackElements;
int count1,count2;
};
template <typename T>
dualStack<T>::dualStack():count1(0),count2(0) {}
template< typename T>
void dualStack<T>::push(const T&item, stackNumber n){
if(n==one)
{
dualStackElements.push_front(item);
count1++;
}
else if(n==two)
{
dualStackElements.push_back(item);
count2++;
}
}
template <typename T>
void dualStack<T>::pop(stackNumber n){
if(n==one)
{
dualStackElements.pop_front();
count1--;
}
else if(n==two)
{
dualStackElements.pop_back();
count2--;
}
}
template <typename T>
T& dualStack<T>::top(stackNumber n){
if(n==one)
return dualStackElements.front();
else if(n==two)
return dualStackElements.back();
}
template <typename T>
const T& dualStack<T>::top(stackNumber n) const{
if(n==one)
return dualStackElements.front();
else if(n==two)
return dualStackElements.back();
}
template<typename T>
bool dualStack<T>::empty(stackNumber n) const{
//if(n==one)
if(n==one)
{
if(count1==0)
return true;
else
return false;
}
else if(n==two)
{
if(count2==0)
return true;
else
return false;
}
}
template<typename T>
int dualStack<T>::size(stackNumber n) const{
if(n==one)
return count1;
else if(n==two)
return count2;
}
int main(){
dualStack<int >ds;
//int num=0;
srand(time(NULL));
for(int i = 0; i<20; ++i)
{
int num=rand()%20;
//num++;
if(num%2==1)
ds.push(num,one);
else if(num%2==0)
ds.push(num,two);
}
//看看是否双端栈为空
if(ds.empty(one))
cout<<"奇数列为空!"<<endl;
else
cout<<"奇数列不为空!"<<"且大小为"<<ds.size(one)<<endl;
if(ds.empty(two))
cout<<"偶数列为空!"<<endl;
else
cout<<"偶数列不为空!"<<"且大小为"<<ds.size(two)<<endl;
cout<<"奇数: ";
int size1=ds.size(one);
for(int j = 0; j<size1; ++j){
cout<<ds.top(one)<<" ";
ds.pop(one);
}
cout<<endl;
cout<<"偶数: ";
int size2=ds.size(two);
for(int k = 0; k<size2; ++k){
cout<<ds.top(two)<<" ";
ds.pop(two);
}
cout<<endl;
//看看是否双端栈为空
if(ds.empty(one))
cout<<"奇数列为空!"<<endl;
else
cout<<"奇数列不为空!"<<"且大小为"<<ds.size(one)<<endl;
if(ds.empty(two))
cout<<"偶数列为空!"<<endl;
else
cout<<"偶数列不为空!"<<"且大小为"<<ds.size(two)<<endl;
return 0;
}
双端栈
最新推荐文章于 2022-07-13 17:53:32 发布