设为首页 加入收藏

TOP

c++和数据结构 模拟栈的入栈和出栈
2016-10-10 18:31:42 】 浏览:482
Tags:数据结构 模拟

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<<"入栈成功!!"<
运行结果:

\

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇C/C++的8种排序算法及实现 下一篇C++ Note-Polymorphism-02

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目