原理: 压栈时从链表头结点开始压,弹栈时从头结点往后弹。
-
#include <stdio.h>
-
#include <string.h>
-
#include <stdlib.h>
-
-
/* 栈的最大深度 */
-
#define STACK_DEEP_MAX 256U
-
-
typedef struct tagStackNode{
-
struct tagStackNode *pstNext;
-
int iData;
-
} STACK_NODE_S;
-
-
typedef struct tagStackHead{
-
STACK_NODE_S *pstNext;
-
int iStackDeep;
-
} STACK_HEAD_S;
-
-
static STACK_HEAD_S g_stHead;
-
-
static void stack_AddHead(STACK_HEAD_S *pstHead, STACK_NODE_S *pstAddNode)
-
{
-
pstAddNode->pstNext = pstHead->pstNext;
-
pstHead->pstNext = pstAddNode;
-
-
return;
-
}
-
-
/* 压栈 */
-
void stack_push(STACK_HEAD_S *pstHead, int iData)
-
{
-
STACK_NODE_S *pstNode;
-
-
if (NULL == pstHead || pstHead->iStackDeep > STACK_DEEP_MAX)
-
{
-
return;
-
}
-
-
pstNode = (STACK_NODE_S *)malloc(sizeof(STACK_NODE_S));
-
if (NULL != pstNode)
-
{
-
memset(pstNode, 0, sizeof(*pstNode));
-
pstNode->iData = iData;
-
stack_AddHead(pstHead, pstNode);
-
pstHead->iStackDeep++;
-
}
-
-
return;
-
}
-
-
/* 弹栈 */
-
int stack_popd(STACK_HEAD_S *pstHead)
-
{
-
STACK_NODE_S *pstNode;
-
int iData;
-
-
if (NULL == pstHead || NULL == pstHead->pstNext)
-
{
-
return;
-
}
-
-
pstNode = pstHead->pstNext;
-
pstHead->pstNext = pstHead->pstNext->pstNext;
-
iData = pstNode->iData;
-
free(pstNode);
-
pstHead->iStackDeep--;
-
-
return iData;
-
}
-
-
/* 获取栈深度 */
-
int stack_deep(STACK_HEAD_S *pstHead)
-
{
-
int iStackDeep = -1;
-
-
if (NULL != pstHead)
-
{
-
iStackDeep = pstHead->iStackDeep;
-
}
-
-
return iStackDeep;
-
}
-
-
/* 测试代码 */
-
void stack_test(void)
-
{
-
int iData, iLoop, iDeep, iCount;
-
-
for (iLoop = 0; iLoop < STACK_DEEP_MAX; iLoop++)
-
{
-
stack_push(&g_stHead, iLoop);
-
}
-
-
iCount = 0;
-
iDeep = stack_deep(&g_stHead);
-
printf("the deep of the stack is %d\n", iDeep);
-
for (iLoop = 0; iLoop < iDeep; iLoop++)
-
{
-
iData = stack_popd(&g_stHead);
-
printf("%d\t", iData);
-
iCount++;
-
if (8 == iCount)
-
{
-
iCount = 0;
-
printf("\n");
-
}
-
}
-
printf("\n");
-
-
return;
-
}
-
-
void main(void)
-
{
-
stack_test();
-
-
return;
-
}
阅读(960) | 评论(0) | 转发(0) |