您的位置:首页 > 理论基础 > 数据结构算法

C++数据结构之Stack(栈)

2015-08-21 16:46 609 查看
stack,栈,是好比堆积木似的数据结构,从上之下堆积,取出时按“LIFO”-last int first out后进先出的规则。栈一般为线程所独有,也就是每个线程有其自有的栈,与heap堆一般为共有的不同(heap为进程所用,stack为线程所用?)。

stack主要有四种操作:empty判断栈是否为空;pop将栈顶的元素清除;top显示栈顶的元素(不是取走);push压栈,向栈内增加一个元素。

代码(在eclipse运行通过):

.h头文件

#ifndef STACK
#define STACK

const int maxstack = 10;
enum Error_code {overflow, underflow, success};
typedef int Stack_entry;

class Stack
{
public:
Stack();
bool empty()const;
Error_code pop();
Error_code top(Stack_entry &item)const;// item作为取出值的载体
Error_code push(const Stack_entry &item);// item是放入的值
private:
int count;
Stack_entry entry[maxstack];
};

#endif /* STACK_ */


.cpp实现文件

#include "Stack.h"

Stack::Stack()
{
count = 0;
}
bool Stack::empty()const
{
if(count == 0)
return true;
else
return false;
}
Error_code Stack::pop()
{
if(empty())
return underflow;
else
count--;
return success;
}
Error_code Stack::top(Stack_entry &item)const
{
if(count == 0)
return underflow;
else
item = entry[count - 1];
return success;
}
Error_code Stack::push(const Stack_entry &item)
{
if(count >= maxstack)
return overflow;
else
entry[count++] = item;
// firstly make entry[count] = item,later count + 1
return success;
}


main主程序测试文件:

#include "Stack.h"
#include <cstdio> // or: #include "stdio.h"
//using
int main()
{
Stack mystack;
mystack.push(2);
int a;
mystack.top(a);
printf("%s %d","LvLang",a);

return 0;
}


代码中有一点重要的知识点,就是变量类型模板(不知道专业术语自己扯了这词)Stack_entry,这里的变量类型相当于一个模板,要能运行,必须先实例化这个模板,解决方法是用“typedef”(类型定义),比如:typedef char Stack_entry,这里就将Stack_entry实例化为char变量类型。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: