数据结构应用标准模版库STL——栈(分解栈元素)

来源:互联网 发布:腾讯何时优化吃鸡 编辑:程序博客网 时间:2024/04/30 21:23

我们开发出一种算法: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和17if(uncouple(intStack,14))cout<<"Uncoupled 14"<<endl;elsecout<<"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;}