当前位置: 移动技术网 > IT编程>开发语言>C/C++ > c++和数据结构 模拟栈的入栈和出栈

c++和数据结构 模拟栈的入栈和出栈

2018年11月07日  | 移动技术网IT编程  | 我要评论

蓝月聊天室,庆春电影大世界,葬神空间

c++学了类 老师就让写了这个、、、

#include 
#include 
using namespace std;
class stack
{
	public:
		void push(int x);
		void init();
		int pop();
		struct stack
		{
			int num;
			stack *next ,*pre;
		}*head;
};
//初始化栈顶 
void stack::init()
{
	head=(struct stack *)malloc(sizeof(struct stack));
	head->num=-1;
	head->next=null;
	head->pre=null;
}
//入栈 
void stack::push(int x)
{
	stack *p;
	p=(struct stack *)malloc(sizeof(struct stack));
	head->next=p;
	p->pre=head;
	head=p;
	head->num=x;
}
//出栈 
int stack::pop()
{
	if(head->pre!=null)
	{
		int x=head->num;
		head=head->pre;
		head->next=null;
		return x; 

	}
	else
	{
		return 0x3fffffff;
	}
}
int main()
{ 
	stack s;
	s.init();
	while(true)
	{
		cout<<"向栈中添加元素请按1,取出栈顶元素请按2,退出请按3"<>x;
		if(x==1)
		{
			int y;
			cout<<"请输入入栈的元素:";
			cin>>y;
			s.push(y);
			cout<<"入栈成功!!"<
运行结果:

 

\

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网