<span style="font-family: Arial, Helvetica, sans-serif; font-size: 12px;">7.1 动态内存分配</span></span>
<span style="font-family: Arial, Helvetica, sans-serif; font-size: 12px;">7.1 动态内存分配</span></span>
n,q,i,p 变量都是在栈中分配的
Malloc 200 ,100 是在堆中分配的
<span style="font-size:12px;">void f(int k)
{
int n;
double *q=(double *)malloc(200);
}
void main()
{
int i=10;
int *p=(int *)malloc(100);
}</span>
7.2 栈的初始化
typedef struct node
{
int data;
struct node *pnext;
}NODE,* PNODE;
typedef struct stack //栈的结构,栈顶、栈尾都是指向 结点类型数据
{
PNODE ptop;
PNODE pbuttom;
}STACK,* PSTACK;
void initstack(PSTACK ps);
void push(PSTACK ps,int val);
void traverse(PSTACK ps);
int pop(PSTACK ps,int * pval);
void clear(PSTACK ps);
void main()
{
int val;
STACK s;
initstack(&s);
push(&s,1);
push(&s,5);
push(&s,44);
traverse(&s);
if(pop(&s,&val))
printf("\n%2d出栈\n",val);
if(pop(&s,&val))
printf("%2d出栈\n",val);
if(pop(&s,&val))
printf("%2d出栈\n",val);
if(pop(&s,&val))
printf("%2d出栈\n",val);
printf("执行清空后:");
clear(&s);
}
void initstack(PSTACK ps)
{
//PNODE ptop =(PNODE)malloc(sizeof(NODE));
ps->ptop =(PNODE)malloc(sizeof(NODE));
if(NULL==ps->ptop)
{
printf("初始化内存分配失败\n");
exit(-1);
}
else
{
ps->pbuttom=ps->ptop;
ps->ptop->pnext=NULL; //栈顶和栈底 指向的下一个元素为空
}
}
7.3 Push
为什么next方向要向下呢?如果向上,那么pop时,需要pre指针,而是只有next指针,所以只有这个方向。
{
PNODE pnew =(PNODE)malloc(sizeof(NODE));//创建一个新节点
if(NULL==ps->ptop)
{
printf("压栈时,内存分配失败\n");
exit(-1);
}
else
{
printf("%2d入栈\n",val);
pnew->data=val; //保存push数据
pnew->pnext=ps->ptop;//入栈
ps->ptop=pnew; //栈顶上移
return ;
}
}
7.4 pop
int empty(PSTACK ps)
{
if(ps->ptop==ps->pbuttom) //栈顶与栈底 指针一样 说明栈空
{
printf("栈空\n");
return 1;
}
else return 0;
}
int pop(PSTACK ps,int * pval)
{
if(empty(ps)) //先判断栈是否为空
return 0;
else
{
PNODE p=(PNODE)malloc(sizeof(NODE)); //目的:将删掉的top结点 释放
p=ps->ptop;
*pval=p->data;
ps->ptop=p->pnext; //栈顶下移
free(p); //结点占的空间释放
p=NULL; //指针释放
return 1;
}
}
free只是释放了指向内存的空间 而不是改变指针的指向; p=null 清空指针
7.5 遍历
//栈中元素的遍历void traverse(PSTACK ps)
{
// PNODE p =(PNODE)malloc(sizeof(NODE));//创建一个新节点
PNODE p=ps->ptop;//遍历 不需要内存空间,指针足以
while(p!=ps->pbuttom)
{
printf("%d ",p->data);
p=p->pnext;
}
}
7.6清空
destroy是将所有都释放,包括栈顶和栈底
//清空把栈中数据清空,释放内存,栈顶指向栈底
void clear(PSTACK ps)
{
PNODE p=ps->ptop;
PNODE q=NULL;
if(empty(ps)) //先判断栈是否为空
return ;
else
{
while(p!=ps->pbuttom)
{
q=p;
p=p->pnext;
free(q);
}
ps->ptop=ps->pbuttom;
}
}
void clear(PSTACK ps)
{
PNODE p=ps->ptop;
PNODE q=NULL;
if(empty(ps)) //先判断栈是否为空
return ;
else
{
while(p!=ps->pbuttom)
{
q=p;
p=p->pnext;
free(q);
}
ps->ptop=ps->pbuttom;
}
}