【摘要】链表存储结构的内存地址不一定是连续的,但顺序存储结构的内存地址一定是连续的;链式存储适用于在较频繁地插入、删除、更新元素时,而顺序存储结构适用于频繁查询时使用。所以本文主要基于前文的基础,讨论链式存储结构的堆栈。
/*链式结构*/
typedef struct _STACK_NODE
{
int pData;
struct _STACK_NODE *next;
}STACK_NODE,*LinkStackPtr;
typedef struct LinkStack
{
LinkStackPtr top;//栈顶指针的位置
int count; //统计当前堆栈中包含多少数据
}LinkStack;
(2)初始化堆栈
STATUS init_stack(LinkStack pStackNode)
{
pStackNode->top= NULL;//空栈,头指针指向空
pStackNode->count = 0;
return OK;
}
(3)释放堆栈
STATUS free_stack(LinkStack* pStackNode)
{
LinkStackPtr *p = NULL;
if(NULL == pStackNode)
return FALSE;
assert(NULL != pStackNode->top);
p = pStackNode->top->next; //保存下一个结点
while(pStackNode->count && p){
p = pStackNode->top->next;//保存
free(pStackNode->top);
pStackNode->top = p;//重新赋值栈顶指针
pStackNode->count--;
}
return TRUE;
}
(4)堆栈压入数据
STATUS stack_push(LinkStack* pStackNode, int value)
{
LinkStackPtr *p;
p = (LinkStackPtr*)malloc(sizeof(LinkStackPtr));
if(NULL == p)
return FALSE;
p->pData = value;//赋值
p->next = pStackNode->top;//当前的栈顶元素赋值给新结点如图①
pStackNode->top = p;//新结点赋值给栈顶元素,如图②
pStackNode->count++;
return TRUE;
}
(5)堆栈弹出数据
STATUS stack_pop(LinkStack* pStackNode, int* value)
{
LinkStackPtr *p;
if(NULL == pStackNode || NULL == value)
return FALSE;
*value = pStackNode->top->data;//返回值
p = pStackNode->top;
pStackNode->top = pStackNode->top->next;
free(p);
p = NULL;
pStackNode->count--;
return TRUE;
}
(6)统计当前堆栈中包含多少数据
int count_stack_number(const LinkStack* pStackNode)
{
return pStackNode->count;
}
原文地址:http://blog.csdn.net/xy010902100449/article/details/46558285