栈
栈类似于箱子。
静态栈、动态栈。
关于栈的操作
#include<stdio.h> #include<malloc.h> #include<stdlib.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 empty(PSTACK); bool pop(PSTACK, int *); void clear(PSTACK p); int main(void) { STACK s; int val; init(&s); push(&s, 1); push(&s, 2); push(&s, 3); push(&s, 4); push(&s, 5); push(&s, 6); push(&s, 7); traverse(&s); if(pop(&s, &val)) { printf("出栈成功,出栈的元素是 %d \n", val); } else { printf("出栈失败\n"); } traverse(&s); clear(&s); if(pop(&s, &val)) { printf("出栈成功,出栈的元素是 %d \n", val); } else { printf("出栈失败\n"); } return 0; } //完成一个栈的初始化 void init(PSTACK p) { p->pTop = (PNODE)malloc(sizeof(NODE)); if(NULL == p->pTop) { printf("动态内存分配失败\n"); exit(-1); } else { p->pBottom = p->pTop; p->pTop->pNext = NULL; } } void push(PSTACK p, int val) { PNODE pNew = (PNODE)malloc(sizeof(NODE)); pNew->data = val; pNew->pNext = p->pTop; p->pTop = pNew; } void traverse(PSTACK p) { PNODE r = p->pTop; while(r != p->pBottom) { printf("%d ", r->data); r = r->pNext; } printf("\n"); return; } bool empty(PSTACK p) { if(p->pTop == p->pBottom) return true; else return false; } //把p所指向的栈出栈一次,并把出栈的元素存入pval形参所指的变量中 bool pop(PSTACK p, int * pval) { if(empty(p)) { return false; } else { PNODE r = p->pTop; *pval = r->data; p->pTop = r->pNext; free(r); r = NULL; return true; } } void clear(PSTACK p) { if(empty(p)) { return; } else { PNODE r = p->pTop; PNODE t = NULL; while(r != p->pBottom) { t = r->pNext; free(r); r = t; } p->pTop = p->pBottom; } }
栈主要用于表达式求值,缓冲处理,迷宫,函数调用,中断...
时间: 2024-11-05 15:00:19