栈是个好东西,后进先出是其精髓,今天就来点比较基础的东西,先来解决入栈和出栈问题
#include <iostream>
#include <stdlib.h>
using namespace std;
//重中之重,先定义一个类
class Stack
{
public:
void push(int x);//入栈需要参数,不要忘了
int pop();//出栈不需要参数
//还要对栈进行初始化
void init();
struct stack
{
int num;//栈存的内容
stack *next, *prev;
}*top;
};
//首先对成员函数init()进行初始化
void Stack::init()
{
//第一步进行分配内存空间,其实用new让系统自动分配空间个人感觉会更好
top = (struct stack *)malloc(sizeof(struct stack));
top->num = -1;
top->prev = NULL;
top->next = NULL;
}
//首先进行入栈
void Stack::push(int x)
{
stack *p;
p = (struct stack *)malloc(sizeof(struct stack));
top->next = p;
p->prev = top;
top = p;
top->num = x;
}
//进行出栈
int Stack::pop()
{
if (top->prev != NULL)
{
int x = top->num;
top = top->prev;
top->next = NULL;
return x;
}
else
{
return 6666666;
}
}
int main()
{
Stack s;
//首先进行初始化
s.init();
while (1)
{
cout << "入栈请输入1,出栈请输入2,退出请输入3" << endl;
int k;
cin >> k;
if (k == 1)
{
int x;
cout << "请输入入栈的元素:";
cin >> x;
s.push(x);
cout << "入栈操作成功!" << endl;
}
if (k == 2)
{
int top = s.pop();
if (top == 6666666)
{
cout << "对不起,当前栈为空,不能出栈,否则产生错误!" << endl;
}
else
{
cout << "出栈操作成功! 当前栈顶元素为: " << top << endl;
}
}
if (k == 3)
{
cout << "退出成功,谢谢" << endl;
break;
}
}
return 0;
}
让我们来看看运行结果
![微笑](http://static.blog.csdn.net/xheditor/xheditor_emot/default/smile.gif)