数据结构—线性结构之栈

    科技2024-08-16  28

    1、栈的定义 一种可以实现“先进后出”的存储结构,类似于箱子中存放物品,先放进去的物品只能够最后拿出来,后放进去的物品可以先拿出来。

    2、栈的分类 (1)静态栈 (2)动态栈

    3、栈的算法 (1)出栈 (2)压栈 4、栈的应用 (1)函数调用 (2)中断 (3)表达式求值 (4)分配内存 (5)缓冲处理 (6)迷宫 栈的操作实现代码(C语言)

    #include <stdio.h> #include <stdlib.h> #include <malloc.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 *); bool empty(PSTACK); void clear(PSTACK); int main(void) { STACK S; //STACK 等价于struct Stack int val; init(&S); //初始化栈 push(&S,1); push(&S,2); push(&S,3); push(&S,4); push(&S,5); push(&S,6); traverse(&S); printf("执行清空操作!\n"); clear(&S); /* if( pop(&S,&val) ) { printf("出栈成功,出栈的元素是%d \n",val); } else { printf("出栈失败!\n"); } */ traverse(&S); return 0; } 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; } } 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; } bool pop(PSTACK pS,int * pVal) { if(empty(pS)) { return false; } else { PNODE r = pS->pTop; *pVal = r->data; pS->pTop = r->pNext; free(r); r = 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; } }

    静态内存(或局部变量)由栈分配,动态分配由堆分配

    Processed: 0.013, SQL: 8