前面咱們講到了隊列,今天咱們接着討論另一種數據結構:堆棧。堆棧幾乎是程序設計的命脈,沒有堆棧就沒有函數調用,固然也就沒有軟件設計。那麼堆棧有什麼特殊的屬性呢?其實,堆棧的屬性主要表如今下面兩個方面:數據結構
(1)堆棧的數據是先入後出函數
(2)堆棧的長度取決於棧頂的高度spa
那麼,做爲連續內存類型的堆棧應該怎麼設計呢?你們能夠本身先試一下:.net
(1)設計堆棧節點設計
- typedef struct _STACK_NODE
- {
- int* pData;
- int length;
- int top;
- }STACK_NODE;
(2)建立堆棧blog
- 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)統計當前堆棧中包含多少數據get
- int count_stack_number(const STACK_NODE* pStackNode)
- {
- return pStackNode->top;
- }
建議: 堆棧是函數調用的基礎,是遞歸調用的基礎,是不少問題的根源,建議朋友們平時有時間好好練習一下。
轉自:http://blog.csdn.net/feixiaoxing/article/details/6847998