定義:一種可以實現“ 先進後出 ”的存儲結構 分類: 1. 靜態棧 2. 動態棧 演算法: 1. 出棧 2. 壓棧 代碼實現: 多敲,多敲 ,後期改進 應用: 1. 函數調用 2. 中斷 3. 表達式求值 4. 記憶體分配 5. 緩衝處理 6. 迷宮 ...
定義:一種可以實現“先進後出”的存儲結構
分類:
- 靜態棧
- 動態棧
演算法:
- 出棧
- 壓棧
代碼實現:
多敲,多敲,後期改進
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct Node
{
int data;
struct Node * pNext;
}NODE , * PNODE;
typedef struct Stack
{
PNODE pTop;
PNODE pBottom;
}STACK , * PSTACK;
void init(PSTACK);
void push(PSTACK , int);
void traverse(PSTACK);
bool pop(PSTACK , int *);
void clear(PSTACK pS);
int main(void)
{
STACK S; // STACK等價於 struct Stack
int val;
init(&S); // 目的是造出一個空棧
push(&S , 1); // 壓棧
push(&S , 8);
push(&S , 23);
push(&S , 26);
push(&S , 34);
push(&S , 45);
push(&S , 76);
push(&S , 88);
traverse(&S); // 遍歷輸出
if(pop(&S , &val))
{
printf("你刪除的是%d\n", val );
traverse(&S);
printf("清空數據\n");
clear(&S);
traverse(&S);
}
else
{
printf("刪除失敗\n");
}
}
void init(PSTACK pS)
{
pS->pTop = (PNODE)malloc(sizeof(NODE));
if (NULL == pS->pTop)
{
printf("動態記憶體分配失敗\n");
exit(-1);
}
else
{
pS->pBottom = pS->pTop;
pS->pTop->pNext = NULL; // pS->pBottom->pNext = NULL
}
}
void push(PSTACK pS, int val)
{
PNODE pNew = (PNODE)malloc(sizeof(NODE));
pNew->data = val;
pNew->pNext = pS->pTop; // 這裡需要註意
pS->pTop = pNew;
return;
}
void traverse(PSTACK pS)
{
PNODE p = pS->pTop;
while(p != pS->pBottom)
{
printf("%d ", p->data);
p = p->pNext;
}
printf("\n");
return;
}
bool empty(PSTACK pS )
{
if (pS->pTop == pS->pBottom)
return true;
else
return false;
}
// 把pS所指向的棧出棧一次,並把出棧元素存下
bool pop(PSTACK pS , int *val)
{
if (empty(pS))
{
return false;
}
else
{
PNODE p = pS->pTop;
*val = p->data;
pS->pTop = p->pNext;
free(p);
p = NULL;
return true;
}
}
// 清空
void clear(PSTACK pS)
{
if (empty(pS))
{
return;
}
else
{
PNODE p = pS->pTop;
PNODE q = NULL;
while(p != pS->pBottom)
{
q = p->pNext;
free(p);
p = q;
}
pS->pTop = pS->pBottom;
}
}
應用:
- 函數調用
- 中斷
- 表達式求值
- 記憶體分配
- 緩衝處理
- 迷宮