首页 > 学院 > 开发设计 > 正文

利用一个栈倒序另外一个栈中的数

2019-11-06 07:06:47
字体:
来源:转载
供稿:网友
题目:有两个相同的栈A和B,在栈A中存放着从大到小的数:1,2,3,4,5,栈顶为最小数1,另外一个栈B为空的。现在要求不使用其他的数据结构,将栈A中的数字顺序倒过来,使其栈顶的数为最大值5。
#include <iostream.h>#include <stdlib.h>#include <stack>using namespace std;template <typename T>void ReverSEOrder(stack<T>&s1,stack<T>&s2){	s1.push(5);	s1.push(4);	s1.push(3);	s1.push(2);	s1.push(1);	int sortNum=0;	int oriStackSize=s1.size();	while(sortNum<oriStackSize){		int temp=s1.top();		s1.pop();		while(s1.size()-sortNum>0)		{			s2.push(s1.top());			s1.pop();		}		s1.push(temp);		++sortNum;		while(!s2.empty())		{			s1.push(s2.top());			s2.pop();		}	}	cout<<"逆序栈输出:"<<endl;	while(!s1.empty())	{		cout<<s1.top()<<endl;		s1.pop();	}}void main(){	stack<int> s1;	stack<int> s2;	ReverseOrder(s1,s2);}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表