栈 Stack
定义:
一种可以实现先进后出的存储结构
分类:
静态栈: 以数组来作为内核实现
动态栈:以链表来作为内核实现
应用:
函数调用
中断?
表达式求值
内存分配
缓冲处理
迷宫?
#include <stdio.h> #include <malloc.h> #include <stdlib.h> typedef enum { true = 1, false = 0 } boolean; typedef struct Node { int data; struct Node * pNext; } * PNODE, NODE; typedef struct Stack { PNODE upNode; PNODE downNode; } * PSTACK, STACK; boolean isEmpty(PSTACK pstack); void safeCheck(PSTACK pstack); void createStack(PSTACK pstack); void pushStack(PSTACK pstack, int value); boolean popStack(PSTACK pstack, int * pData); void traverseStack(PSTACK pstack); void clearStack(PSTACK pstack); int main() { STACK stack; createStack(&stack); pushStack(&stack, 10); pushStack(&stack, 40); pushStack(&stack, 20); pushStack(&stack, 30); traverseStack(&stack); int t; popStack(&stack, &t); printf("%d ", t); traverseStack(&stack); clearStack(&stack); traverseStack(&stack); return 0; } void safeCheck(PSTACK pstack){ if (NULL == pstack -> upNode) { printf("内存分配失败 "); exit(-1); } } /** * 创建堆 * @param pstack */ void createStack(PSTACK pstack){ pstack -> upNode = (PNODE)malloc(sizeof(NODE)); safeCheck(pstack); pstack -> downNode = pstack -> upNode; pstack -> upNode -> pNext = NULL; } /** * * @param pstack * @param value */ void pushStack(PSTACK pstack, int value){ PNODE newNode = (PNODE)malloc(sizeof(NODE)); newNode -> data = value; newNode -> pNext = pstack -> upNode; pstack -> upNode = newNode; } /** * 出栈, 要保存的数据 * @param pstack * @param data */ boolean popStack(PSTACK pstack, int * pData) { if (isEmpty(pstack)) return false; PNODE head = pstack -> upNode; pstack -> upNode = head -> pNext; *pData = head -> data; free(head); head = NULL; return true; } /** * 输出栈 * @param pstack */ void traverseStack(PSTACK pstack) { if (isEmpty(pstack)) { printf("[]"); return; } PNODE tempNode = pstack -> upNode; printf("["); while (tempNode != pstack -> downNode) { if (tempNode -> pNext == pstack -> downNode) { printf("%d] ", tempNode -> data); break; } printf("%d,", tempNode -> data); tempNode = tempNode -> pNext; } } /** * 判断是否空栈 * @param pstack * @return */ boolean isEmpty(PSTACK pstack) { return pstack -> upNode == pstack -> downNode; } /** * 清空栈 * @param pstack */ void clearStack(PSTACK pstack) { if (isEmpty(pstack)) return; PNODE iterator = pstack -> upNode; PNODE iterator2 = NULL; while (iterator != pstack -> downNode) { iterator2 = iterator -> pNext; free(iterator); iterator = iterator2; } pstack -> upNode = pstack -> downNode; }