您的位置:首页 > 其它

重新教自己学算法之线性堆栈(八)

2015-05-24 22:19 316 查看
#include <iostream>
#include <cstdlib>
#include <cassert>
#include <cstring>
using namespace std;

#define STATUS int
#define TRUE 1
#define FALSE 0

typedef struct _STACK_NODE
{
int* pData;
int length;
int top;
}STACK_NODE;

STACK_NODE* alloca_stack(int number)
{
STACK_NODE* pStackNode = NULL;
if(0 == number)
return NULL;
pStackNode = (STACK_NODE*)malloc(sizeof(STACK_NODE));
assert(NULL != pStackNode);
memset(pStackNode, 0, sizeof(STACK_NODE));

pStackNode->pData = (int*)malloc(sizeof(int) * number);
if(NULL == pStackNode->pData)
{
free(pStackNode);
return NULL;
}

memset(pStackNode->pData, 0, sizeof(int) * number);
pStackNode->length = number;
pStackNode->top = 0;
return pStackNode;
}

STATUS free_stack(STACK_NODE* pStackNode)
{
if(NULL == pStackNode)
return FALSE;

assert(NULL != pStackNode->pData);

free(pStackNode->pData);
free((void*)pStackNode);
return TRUE;
}

STATUS stack_push(STACK_NODE* pStackNode, int value)
{
if(NULL == pStackNode)
return FALSE;

if(pStackNode->length == pStackNode->top)
return FALSE;

pStackNode->pData[pStackNode->top++] = value; //后自增,先使用在自增
return TRUE;
}

STATUS stack_pop(STACK_NODE* pStackNode, int* value)
{
if(NULL == pStackNode || NULL == value)
return FALSE;

if(0 == pStackNode->top)
return FALSE;

*value = pStackNode->pData[-- pStackNode->top]; //先自减,再运算
return TRUE;
}

int const_stack_number(const STACK_NODE* pStackNode)
{
return pStackNode->top;
}
void output_stack(const STACK_NODE* pStackNode)
{
for (int i = 0; i < pStackNode->length; ++i)
{
cout<<pStackNode->pData[i]<<"  ";
}
cout<<endl;
}

int main()
{
STACK_NODE* pStackNode = alloca_stack(3);

cout<<const_stack_number(pStackNode)<<endl;;  //0
stack_push(pStackNode, 20);
stack_push(pStackNode, 15);
output_stack(pStackNode); //20,15,0
stack_push(pStackNode,30);
cout<<const_stack_number(pStackNode)<<endl; // 3
output_stack(pStackNode); //20,15,30
stack_push(pStackNode,45);
output_stack(pStackNode);   //栈已满 20 15 30
int* number;
stack_pop(pStackNode,number);
cout<<*number<<endl;  //  30
output_stack(pStackNode);
stack_push(pStackNode,45);   //20,15,45
output_stack(pStackNode);
cout<<const_stack_number(pStackNode)<<endl;   //3
cout<<pStackNode->pData<<endl;          //0x4d24b0
cout<<&(pStackNode->pData[0])<<endl;    //0x4d24b0
cout<<&(pStackNode->pData[1])<<endl;    //0x4d24b4
cout<<(pStackNode->pData + 2)<<endl;    //0x4d24b8
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  线性堆栈