⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 stack.cpp

📁 从键盘上输 入一串正整数
💻 CPP
字号:
#include <iostream.h>
#include <stdlib.h>
static const int initialsize=200;
template <class ElemType>class stack{
	friend ostream &operator<<(ostream & os,stack<ElemType> & st);

private:
	ElemType *Array;
	int top;
	bool location;
public:
	stack(int t,bool loc,ElemType * Arr)
	{top=t;location=loc;Array=Arr;}
	~stack(){}
	int topnum(){return top;}
const  ElemType &Top() const;
	void Push(const ElemType &x,stack<ElemType> & st);
	void Pop();
};
template <class ElemType>	
ostream &operator<<(ostream & os,stack<ElemType> & st)
{
	if(st.location==0)
	{
	for(int i=st.topnum();i>=0;i--)
	{
	os<<st.Top()<<' ';
	st.Pop();
	}
	}
	else
	{
			for(int i=st.topnum();i<=initialsize;i++)
	{
	os<<st.Top()<<' ';
	st.Pop();
	}
	}
	return os;
}
template <class ElemType>
 const ElemType & stack<ElemType>::Top() const {
	if(top==-1||top==201)
	{
	cout<<"Underflow:Stack is empty!"<<endl;
	exit(0);
	}
	return Array[top];
}
template <class ElemType>
void stack<ElemType>::Pop()
{
	if(top==-1||top==201)
	{
		cout<<"Underflow:Stack is empty!"<<endl;
	exit(0);
  }
		if(location==0)
		top--;
	else
		top++;
}
template <class ElemType>
void stack<ElemType>::Push(const ElemType &x,stack<ElemType> & st)
{
	if((top+1==st.topnum())&&(top-1==st.topnum()))
	{
		cout<<"Space is used out!!"<<endl;
		exit(0);
	}
	if(location==0)
	{
		top++;
		Array[top]=x;
	}
	else
	{
		top--;
		Array[top]=x;
	}
}
main()
{
	int*array;
	array=new int [200];
	stack<int> st1(-1,0,array),st2(201,1,array);
	cout<<"This is Push operation!"<<endl;
	int et=0;
	cout<<"Please input element of the stack one by one!,-10000 to stop  input"<<endl;
	cin>>et;
	while(et!=-10000)
	{st1.Push(et,st2);
		cin>>et;
		
	}
	cout<<"Please input another element of the stack one by one!,-10000 to stop  input"<<endl;
	et=0;
	cin>>et;
	while(et!=-10000)
	{st2.Push(et,st1);
		cin>>et;
		
	}
	cout<<"This is Pop operation!"<<endl;
	cout<<st1;
	cout<<st2;
	return 0;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -