定义:一种可以实现“先进后出”的存储结构。
分类:
静态栈[数组]
动态栈[链表,重要]
算法:
出栈
压栈
应用:
c程序实现链表的栈操作
栈原理:
初始化原理:
压栈原理:
遍历链栈:
出栈原理:
实现程序:
#include <stdio.h> #include <malloc.h> #include <stdlib.h> #define bool int #define true 1 #define false 0 // 链表栈 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); int main(void) { STACK S; // STACK等价于struct Stack int val; init(&S); // 压栈 push(&S, 1); // 把1放进去 push(&S, 2); // 把2放进去 push(&S, 3); push(&S, 4); push(&S, 5); push(&S, 6); /* // 遍历输出 traverse(&S); // 出栈 if(pop(&S, &val)) printf("出栈成功,出栈的元素是%d ", val); else printf("出栈失败 "); */ clear(&S); // 遍历输出 traverse(&S); return 0; } void init(PSTACK pS) { pS->pTop = (PNODE)malloc(sizeof(NODE)); if(pS->pTop == NULL) { printf("动态内存分配失败! "); 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(" "); return; } // 判断是否为空 bool empty(PSTACK pS) { if(pS->pTop == pS->pBottom) return true; else return false; } // 把pS所指向的栈出栈一次,并把出栈的元素存入pVal形参所指向的变量中, // 如果出栈失败,返回false,否则返回true 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; } }