栈和队列是一种特殊的线性结构,是连续存储或离散存储的一种应用。
此为链式队列。
定义
一种可以实现“先进后出”的存储结构,类似于箱子。
分类
算法
应用
- 函数调用
- 中断
- 表达式求值
- 分配内存
- 缓冲处理
- 迷宫
举例
int main(void) { int p; int * m = (int *)malloc(100); }
|
如静态变量p和m是在栈中分配,由操作系统自动分配和释放。而(int *)malloc(100);
执行后,将在堆中分配一块100字节的内存,由程序员手动分配。
代码
#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 pS); bool Pop(PSTACK, int *); void Clear(PSTACK pS);
int main(void) { STACK s;
int val;
Init(&s); Push(&s, 1); Push(&s, 2); Push(&s, 3); Push(&s, 4); Traverse(&s);
if(Pop(&s, &val)) { printf("出栈成功!出栈的元素是:%d\n", val); } else printf("出栈失败!\n"); Clear(&s); Traverse(&s); if(Pop(&s, &val)) { printf("出栈成功!出栈的元素是:%d\n", val); } else printf("出栈失败!\n"); 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->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; }
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; } }
|