温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

编程开发中如何实现栈

发布时间:2021-10-21 11:27:55 来源:亿速云 阅读:110 作者:小新 栏目:编程语言

这篇文章主要介绍了编程开发中如何实现栈,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。

/*****************************              WZ ASUST 2016
         
*****************************/
 #include <iostream>  
using namespace std;
const int StackSize=10;  
template <class T>        
class SeqStack
{
public:
    SeqStack( ) ;            //构造函数,栈的初始化
	~SeqStack( );            //析构函数
    void Push(T x);          //将元素x入栈
    T Pop( );                //将栈顶元素弹出
    T GetTop( );	         //取栈顶元素(并不删除)
	bool Empty( );           //判断栈是否为空
private:
    T data[StackSize];      //存放栈元素的数组
    int top;                //栈顶指针,指示栈顶元素在数组中的下标
};
 
template <class T>
SeqStack<T>::SeqStack( )
{
	top=-1;
}
 
template <class T>
SeqStack<T>::~SeqStack( )
{
}
 
template <class T>
void SeqStack<T>::Push(T x)
{
    if (top== StackSize-1) throw "上溢";
    top++;
    data[top]=x;
}
 
template <class T>
T SeqStack<T>::Pop( )
{
    T x;
    if (top==-1) throw "下溢";
    x=data[top--];
    return x;
}
 
template <class T>
T SeqStack<T>::GetTop( )
{
	if (top!=-1)  
    return data[top];
}
 
template <class T>
bool SeqStack<T>::Empty( )
{
	if(top==-1) return 1;
	else return 0;
}
 
void test1()
{    
    SeqStack<int> a;      //创建模板类的实例
   
    if (a.Empty( )){
	
		cout<<"栈空,执行入栈操作:"<<endl;
    	cout<<"对15和10执行入栈操作:"<<endl;
	    try
		{
			a.Push(15);
	        a.Push(10);  
		}
		catch(char* wrong)
		{
			cout<< wrong;
		}
		
		cout<<"栈顶元素为:"<<endl;   //取栈顶元素
		cout<<a.GetTop( )<<endl;
		    
	    cout<<"执行出栈操作:"<<endl;
	    cout<<a.Pop( )<<endl;          //执行出栈操作
        cout<<"栈顶元素为:"<<endl;
	    cout<<a.GetTop( )<<endl;	
	}
	else{
	
		cout<<"栈不空"<<endl;
	}
}
int main()
{
test1();
return 0;
}

感谢你能够认真阅读完这篇文章,希望小编分享的“编程开发中如何实现栈”这篇文章对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,更多相关知识等着你来学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI