郝斌版《数据结构》学习笔记
时间:2015.08.31 - 2015.09.05
栈:一种可以实现“先进后出”的存储结构,类似于箱子(只有一个口进出)。
队列:“先进先出”(两个口,一个口进,一个口出,时间相关的适用)。
分类:静态栈,动态栈。
算法
出栈
压栈
应用
函数调用(顺序,函数的形参压入栈中)
中断
表达式求值(真的算法)
内存分配
缓存处理
迷宫(真的算法)
init() 初始化
删除,pTop指针下移;
增加,则生成节点,pTop指针上移
为空,pTop == pBottom
push 压栈
traverse() 遍历
pop() 出栈
clear() 清空
#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 is_empty(PSTACK);
bool pop(PSTACK, int *); //出栈
void clear(PSTACK); //数据清空
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);
traverse(&S);
if(pop(&S, &val))
printf("pop succeed, the pop is: %d\n", val);
else
printf("pop failed");
traverse(&S); //遍历输出
clear(&S);
printf("after clear:\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; //也可写ps->pBottom->pNext = NULL,此时pTop==pBottom
}
}
void push(PSTACK pS, int val)
{
PNODE pNew = (PNODE)malloc(sizeof(NODE));
pNew->data = val;
pNew->pNext = pS->pTop; //pS->Top不能改为pS->pBottom
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 is_empty(PSTACK pS)
{
if (pS->pTop == pS->pBottom)
return true;
else
return false;
}
bool pop(PSTACK pS, int * pVal)
{
if (is_empty(pS)) //pS本身存放的就是S的地址
{
return false;
}
else
{
//定义r, 释放内存
PNODE r = pS->pTop; //pBottom的值永远不需要改变
*pVal = r->data;
pS->pTop = r->pNext;
free(r);
r = NULL;
return true;
}
}
void clear(PSTACK pS)
{
if (is_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;
}
}