我们开发出一种算法:uncouple(),它使用辅助栈查找和从当前栈中删除第一次出现的元素target。重复地删除栈顶部的元素,并将其推入到辅助栈中,知道找到target.使target从原来的栈中出栈,然后按次序将辅助栈中每个元素推入到原来的栈。如果发生了分解操作,函数返回true,否则返回false;
#include<iostream>
#include<stack>
using namespace std;
template<typename T>
bool uncouple(stack<T>&s,const T&target)
{
stack<T> temStk;
bool foundTarget = true;
while(!s.empty()&&s.top()!=target)
{
temStk.push(s.top());
s.pop();
}
if(!s.empty())
s.pop();
else
foundTarget = false;
while(!temStk.empty())
{
s.push(temStk.top());
temStk.pop();
}
return foundTarget;
}
template <typename T>
void writeArray(const T& array,int & size)
{
int i;
for(i=0;i<size;i++)
cout<<array[i]<<" ";
cout<<endl;
}
int main()
{
int arr[]={19,14,37,43,11,12},i;
int arrsize=sizeof(arr)/sizeof(int);
stack<int > intStack;
cout<<"Creating a stack with values(top to bottom): ";
writeArray(arr,arrsize);
cout<<endl;
//将arr中的各项按arr[arrsize-1]...arr[0]的顺序压入intStack栈中,所以,arr[0]在栈顶
for(i=arrsize-1;i>=0;i--)
intStack.push(arr[i]);
//尝试从intStack中删除14和17
if(uncouple(intStack,14))
cout<<"Uncoupled 14"<<endl;
else
cout<<"14 is not on the stack"<<endl;
if(uncouple(intStack ,17))
cout<<"Uncoupled 17"<<endl;
else cout<<"17 is not on the stack"<<endl;
cout<<"Final stack(top to bottom): ";
while(!intStack.empty())
{
cout<<intStack.top()<<' ';
intStack.pop();
}
cout<<endl;
return 0;
}