链栈的基本操作

链栈的基本操作_第1张图片

#include
#include
#include

#define MAX 100

//栈的数据类型
typedef struct
{
	char name[20];
	float score;
}SElemType;
//链栈的数据类型C语言描述

typedef struct stack
{

	SElemType data;
	struct snode *next;
}Snode,*LinkStack;
//1.初始化操作
void initLinkStak(LinkStack *LS)
{
	*LS=NULL; 
}
//2.判断栈是否空
int LinkStackEmpty(LinkStack LS)
{
	if(LS==NULL) return 1;
	else return 0;
}
//3.得到栈顶
int LinkStackGetTop(LinkStack LS,SElemType *e)
{
	if(LS==NULL) return 0;
	*e=LS->data;return 1;
}
//4.求栈的长度
int LinkListLength(LinkStack LS)
{
	LinkStack p=LS;
	int n=0;
	while(p){n++;p=p->next;}
	return n;
}
//5.进栈
void Push(LinkStack *LS,SElemType e)
{
	//生成新的结点插入到原来的第一个节点之前,头插法
	LinkStack p=(LinkStack)malloc(sizeof(Snode));
	p->data=e;
	p->next=*LS;*LS=p;
}
//6.出栈
void Pop(LinkStack *LS,SElemType *e)
{
	LinkStack p=*LS;
	if(*LS==NULL)return 0;
	*LS=(*LS)->next;
	*e=p->data;
	free(p);
	return 1;
}
//7.遍历
void LinkStackTraverse(LinkStack S)
{
	LinkStack p=S;
	if(S==NULL){printf("栈空!\n");return 0;}
	while(p)
	{
		printf("%s %7.2f\n",p->data.name,p->data.score);
		p=p->next;
	}
	return 1;
}
void main()
{
	LinkStack LS;
	SElemType e1,e2,e3,e4,etop;
	strcpy(e1.name,"A");
	strcpy(e2.name,"B");
	strcpy(e3.name,"C");
	strcpy(e4.name,"D");
	e1.score=87.44;
	e2.score=69.22;
	e3.score=56.33;
	e4.score=89.22;
	initLinkStak(&LS);  //&LS指向指针的指针

	Push(&LS,e1);Push(&LS,e2);Push(&LS,e3);Push(&LS,e4);
	LinkStackTraverse(LS);
	printf("\n");
	Pop(&LS,&e1);
	LinkStackTraverse(LS);
}

运行结果

链栈的基本操作_第2张图片

你可能感兴趣的:(数据结构)