码迷,mamicode.com
首页 > 编程语言 > 详细

C语言 栈的初始化,入栈,出栈,判断栈是否为空,清空栈等函数

时间:2020-02-05 00:00:23      阅读:201      评论:0      收藏:0      [点我收藏+]

标签:ini   return   tom   typedef   c语言   clu   pop   判断   turn   

#include <stdio.h>
#include <stdlib.h>

typedef struct Node
{
int data ;
struct Node * pNext;
}*PNODE ,NODE ;

typedef struct stack
{
PNODE pTop;
PNODE pBottom;
}*PSTACK ,STACK;
void init(PSTACK pS);
void push(PSTACK pS,int val);
void show(PSTACK pS);
bool is_empty(PSTACK pS);
bool pop(PSTACK pS,int * pVal);
void clear(PSTACK pS);
int main()
{
STACK S ;//定义了一个静态的栈,是程序员不能自己释放的
int val ;
init(&S);
push(&S,1);
push(&S,2);
push(&S,3);
push(&S,4);
show(&S);
if(pop(&S,&val))
{
printf("出栈成功,出栈的元素是:%d\n",val);
}
else printf("出栈失败!");
show(&S);
clear(&S);
show(&S);
}
void init(PSTACK pS)
{
pS->pTop = (PNODE)malloc(sizeof(NODE));
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 ;
}
void show(PSTACK pS)
{
PNODE p =pS->pTop ;
while(p!=pS->pBottom)
{
printf("%d ",p->data);
p=p->pNext ;
}
printf("\n");
}
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))
{
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(is_empty(pS))
{
return ;
}
else
{
PNODE p =pS->pTop;
PNODE q ;
while(q!=pS->pBottom)
{
q=p->pNext;
free(p);
p=q ;

}
}
pS->pTop=pS->pBottom;
}

C语言 栈的初始化,入栈,出栈,判断栈是否为空,清空栈等函数

标签:ini   return   tom   typedef   c语言   clu   pop   判断   turn   

原文地址:https://www.cnblogs.com/cocobear9/p/12261891.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!