线性堆栈

本文介绍了堆栈数据结构的基本概念及特点,包括先入后出的原则和栈顶决定长度的特性,并提供了创建、释放堆栈及进行数据压入、弹出操作的具体实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前面我们讲到了队列,今天我们接着讨论另外一种数据结构:堆栈。堆栈几乎是程序设计的命脉,没有堆栈就没有函数调用,当然也就没有软件设计。那么堆栈有什么特殊的属性呢?其实,堆栈的属性主要表现在下面两个方面:

    (1)堆栈的数据是先入后出

    (2)堆栈的长度取决于栈顶的高度

    那么,作为连续内存类型的堆栈应该怎么设计呢?大家可以自己先试一下:

    (1)设计堆栈节点

[cpp]  view plain copy
  1. typedef struct _STACK_NODE  
  2. {  
  3.     int* pData;  
  4.     int length;  
  5.     int top;  
  6. }STACK_NODE;  
     (2)创建堆栈

[cpp]  view plain copy
  1. STACK_NODE* alloca_stack(int number)  
  2. {  
  3.     STACK_NODE* pStackNode = NULL;  
  4.     if(0 == number)  
  5.         return NULL;  
  6.       
  7.     pStackNode = (STACK_NODE*)malloc(sizeof(STACK_NODE));  
  8.     assert(NULL != pStackNode);  
  9.     memset(pStackNode, 0, sizeof(STACK_NODE));  
  10.       
  11.     pStackNode->pData = (int*)malloc(sizeof(int) * number);  
  12.     if(NULL == pStackNode->pData){  
  13.         free(pStackNode);  
  14.         return NULL;  
  15.     }  
  16.       
  17.     memset(pStackNode->pData, 0, sizeof(int) * number);  
  18.     pStackNode-> length = number;  
  19.     pStackNode-> top= 0;  
  20.     return pStackNode;  
  21. }  
     (3)释放堆栈

[cpp]  view plain copy
  1. STATUS free_stack(const STACK_NODE* pStackNode)  
  2. {  
  3.     if(NULL == pStackNode)  
  4.         return FALSE;  
  5.       
  6.     assert(NULL != pStackNode->pData);     
  7.           
  8.     free(pStackNode->pData);  
  9.     free((void*)pStackNode);  
  10.     return TRUE;  
  11. }  
     (4)堆栈压入数据

[cpp]  view plain copy
  1. STATUS stack_push(STACK_NODE* pStackNode, int value)  
  2. {  
  3.     if(NULL == pStackNode)  
  4.         return FALSE;  
  5.           
  6.     if(pStackNode->length == pStackNode->top)  
  7.         return FALSE;  
  8.           
  9.     pStackNode->pData[pStackNode->top ++] = value;  
  10.     return TRUE;  
  11. }  
     (5)堆栈弹出数据

[cpp]  view plain copy
  1. STATUS stack_pop(STACK_NODE* pStackNode, int* value)  
  2. {  
  3.     if(NULL == pStackNode || NULL == value)  
  4.         return FALSE;  
  5.           
  6.     if(0 == pStackNode->top)  
  7.         return FALSE;  
  8.           
  9.     *value = pStackNode->pData[-- pStackNode->top];  
  10.     return TRUE;  
  11. }  
     (6)统计当前堆栈中包含多少数据

[cpp]  view plain copy
  1. int count_stack_number(const STACK_NODE* pStackNode)  
  2. {  
  3.     return pStackNode->top;  
  4. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值