栈是一种LIFO的数据结构,支持从栈顶进行数据的压入(入栈)和弹出(出栈),可应用于将递归算法变成非递归,逆波兰后缀表达式等等。
画了张简单的结构图,如下所示:
用C++模板类实现的代码如下所示:
/*
* =====================================================================================
*
* Filename: 3stack.h
*
* Description: template stack baseed of arry
*
* Version: 1.0
* Created: 2012年03月12日 21时00分45秒
* Revision: none
* Compiler: gcc
*
* Author: Lavey Luo (lavey), luoyi.smt@gmail.com
* Organization:
*
* =====================================================================================
*/
#ifndef __STACK_H__
#define __STACK_H__
namespace st
{
#ifndef _STATUS_CONST_
#define _STATUS_CONST_
enum Status
{
OK = 0,
ERROR = -1
};
const int MAX_LEN = 20;
#endif
template<class VALUE_TYPE>
class stack
{
public:
explicit stack():top(-1){};
~stack(){};
public:
/* 初始化顺序线性表 */
Status Init();
/* 若栈S为空栈,则返回OK,否则返回ERROR*/
Status Empty();
/* 把S置为空栈 */
Status Clear();
/* 返回S的元素个数,即栈的长度 */
int Length();
/* 若栈不空,则用e返回S的栈顶元素,并返回OK;否则返回ERROR */
Status GetTop(VALUE_TYPE *e);
/* 插入元素e为新的栈顶元素 */
Status Push(VALUE_TYPE e);
/* 若栈不空,则删除栈顶元素,用e返回其值,并返回OK;否则返回ERROR */
Status Pop(VALUE_TYPE *e);
private:
int top;
VALUE_TYPE data[MAX_LEN];
};
template<class VALUE_TYPE>
Status stack<VALUE_TYPE>::Init()
{
top = -1;
return OK;
}
template<class VALUE_TYPE>
Status stack<VALUE_TYPE>::Empty()
{
if (top == -1)
return OK;
return ERROR;
}
template<class VALUE_TYPE>
Status stack<VALUE_TYPE>::Clear()
{
top=-1;
return OK;
}
template<class VALUE_TYPE>
int stack<VALUE_TYPE>::Length()
{
return top +1;
}
template<class VALUE_TYPE>
Status stack<VALUE_TYPE>::GetTop(VALUE_TYPE* e)
{
if (top == -1) return ERROR;
*e = data[top];
return OK;
}
template<class VALUE_TYPE>
Status stack<VALUE_TYPE>::Pop(VALUE_TYPE* e)
{
if (top == -1) return ERROR;
*e = data[top];
top--;
return OK;
}
template<class VALUE_TYPE>
Status stack<VALUE_TYPE>::Push(VALUE_TYPE e)
{
if (top >= MAX_LEN -1)
return ERROR;
top++;
data[top] = e;
return OK;
}
}
#endif // __STACK_H__
测试用例的代码如下:
/*
* =====================================================================================
*
* Filename: test_stack.cpp
*
* Description: test case of 4stack.h
*
* Version: 1.0
* Created: 2012年03月12日 21时33分36秒
* Revision: none
* Compiler: gcc
*
* Author: Lavey Luo (lavey), luoyi.smt@gmail.com
* Organization:
*
* =====================================================================================
*/
#include "3stack.h"
#include <stdio.h>
int test_stack(int argc, char** argv)
{
st::stack<int> stack;
if (stack.Init() == st::OK)
{
puts("压栈10个元素,1..10");
for(int j=1;j<=10;j++)
stack.Push(j);
int e = 0;
do
{
stack.Pop(&e);
printf("弹出当前的栈顶元素 e=%d\n", e);
} while(stack.Empty() != st::OK);
printf("栈空否:%d(0:空 -1:否)\n", stack.Empty());
stack.GetTop(&e);
printf("栈顶元素 e=%d 栈的长度为%d\n",e,stack.Length());
stack.Clear();
printf("栈空否:%d(0:空 -1:否)\n", stack.Empty());
}
return 0;
}