定義:一種能夠實現「先進後出」的存儲結構算法
分類:函數
算法:code
代碼實現:內存
多敲,多敲,後期改進it
#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; } }
應用:io