您的位置:首页 > 编程语言 > C语言/C++

顺序栈,C++基本实例应用

2015-11-26 21:17 387 查看
还是想自己写写,一来大家可以批评,二来可以监督自己的学习!

参考书目:数据结构(C++描述)胡学钢 人民邮电出版社

栈的基本应用:顺序栈,应用实例,便于理解,没有过多的细节处理。

输入一组数,反序输出。



/************************************************************************/
/* author:冒失的鱼*/
/************************************************************************/
#include <iostream>
#include <stdio.h>
typedef  int dataType;
#define  MaxSize  50

class stack
{
public:
stack();
bool full()const;
bool empty()const;
dataType getTopData(dataType &varial);
void pop();
void push(const dataType varial);
private:
int count;
dataType data[MaxSize];
};

stack::stack()
{
count = 0;
}

bool stack::full()const
{
if(MaxSize == count)
return true;
return false;
}

bool stack::empty()const
{
if(0 == count)
return true;
return false;
}

dataType stack::getTopData(dataType &varial)
{
if (empty())
std::cout<<"Underflow";

varial = data[count-1];

return varial;
}

void stack::pop()
{
if (empty())
std::cout<<"Underflow";
--count ;
}

void stack::push(const dataType varial)
{
if (full())
std::cout<<"Overflow";

data[count] = varial;
count ++;

}

int main()
{
stack sta;

int n=0,x=0;
std::cout<<"Please input number:";
std::cin>>n;

for (int i=1;i<=n;i++)
{
std::cin>>x;
sta.push(x);
}

while (sta.empty()!=true)
{
//std::cout<<sta.getTopData(x);
sta.getTopData(x);
std::cout<<x;
sta.pop();
}

return 0;
}


dataType getTopData(dataType &varial);函数如果去掉&符,运行结果就会出现问题,涉及到了地址的问题。用传址的方式改变变量的值,很多书都讲过这个问题。

多有不足,希望指导!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: