您的位置:首页 > 其它

链式堆栈的实现 (带头节点的链式堆栈)

2010-09-27 17:47 218 查看
//-----------链式堆栈实现-------------------
//
//  实现的为 带头节点的链式堆栈
//
//
//------------2010年9月27日 17:32:42-------- By AndGod

#include "stdio.h"
#include "malloc.h"

typedef int DataType ; //定义堆栈存储数据类型

typedef struct snode  //定义链式堆栈节点
{
DataType data;
struct snode *next;
}LSNode;

void StackInitiate(LSNode **head)
{
//初始化带头节点的 链式堆栈
*head=(LSNode *)(malloc(sizeof(LSNode)));
(*head)->next=NULL;
}

int StackIsEmpty(LSNode *head)
{
//判断链式堆栈是否为空 --空则返回1,非空则返回0
if(head->next == NULL)
{
return 1;
}
else
{
return 0;
}
}

void StackPush(LSNode *head,DataType x)
{
//进栈------------
LSNode *p;
p=(LSNode*)malloc(sizeof(LSNode));

p->data=x;

p->next=head->next;
head->next=p;
}
int StackPop(LSNode *head,DataType *x)
{
//出栈, 元素由x带出,成功返回 1 失败返回0
if(StackIsEmpty(head))
{
return 0;
}
else
{
*x=(head->next)->data;
head->next=(head->next)->next;

return 1;
}
}

int StackTop(LSNode *head,DataType *x)
{
//查看栈顶元素, 元素由x带出,成功返回 1 失败返回0
if(StackIsEmpty(head))
{
return 0;
}
else
{
*x=head->data;
return 1;
}
}

//测试函数-----------
void main()
{
LSNode *head;
DataType x;

StackInitiate(&head);
for(int i=0; i<20; i++)
{

StackPush(head,i);
}
for(i=0;i<21;i++)
{
if(StackPop(head,&x))
{
printf("出栈%d/n",x);
}
else
{
printf("堆栈已空!/n");
break;
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  null struct 测试 存储 2010