# C++算法之线性堆栈

（1）设计堆栈节点

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

```
``````                                    （2）创建堆栈
``````
```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;
}

```
``````                                    （3）释放堆栈
``````
```STATUS free_stack(const STACK_NODE* pStackNode)
{
if(NULL == pStackNode)
return FALSE;

assert(NULL != pStackNode->pData);

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

```
``````                                    （4）堆栈压入数据
``````
```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;
}

```
``````                                    （5）堆栈弹出数据
``````
```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;
}

```
``````                                    （6）统计当前堆栈中包含多少数据
``````
```int count_stack_number(const STACK_NODE* pStackNode)
{
return pStackNode->top;
}

```
``````                                    建议： 堆栈是函数调用的基础，是递归调用的基础，是很多问题的根源，建议朋友们平时有时间好好练习一下。
``````

0人收藏

0

0