(C语言)栈的链式存储结构的实现

//链式栈的实现
#include
#include
#include

typedef struct Stack_Linklist{
	int data;
	struct Stack_Linklist *next;
}Node,*pNode;

typedef struct Stack{
	pNode pTop;
	pNode pBottom;
}Stack,*pStack;

void Initstack();			//初始化;
int Isempty();				//判断栈是否为空
void Push();				//压栈
int Pop();				//出栈
int Gettop();				//get栈顶元素
void Traverse();			//从栈顶遍历到栈底

int main(void)				//测试
{
	int val;
	Stack s1;
	Initstack(&s1);			//初始化

	if(Isempty(&s1))		//判断栈空
		printf("栈为空!\n");
	else printf("栈不空!\n");

	printf("输入压栈元素:");//压栈1
	scanf("%d",&val);
	Push(&s1,&val);

	printf("输入压栈元素:");//压栈2
	scanf("%d",&val);
	Push(&s1,&val);

	printf("输入压栈元素:");//压栈3
	scanf("%d",&val);
	Push(&s1,&val);

	if(Isempty(&s1))		//判断栈空
		printf("栈为空!\n");
	else printf("栈不空!\n");

	if(Pop(&s1,&val))
		printf("出栈成功,出栈元素为:%d\n",val);
	else printf("栈为空,出栈失败!\n");

	if(Isempty(&s1))		//判断栈空
		printf("栈为空!\n");
	else printf("栈不空!\n");

	if(Gettop(&s1,&val))	//Get栈顶元素
		printf("栈顶元素为%d\n",val);
	else printf("栈为空!\n");
	Traverse(&s1);

	return 0;
}

//初始化,pBottom指向栈底,pTop指向栈顶,栈底元素next指针设置为空
void Initstack(pStack ps1)
{
	ps1->pBottom=(pNode)malloc(sizeof(Node));
	if(ps1->pBottom==NULL){
		printf("动态内存分配失败!\n");
		exit(-1);
	}
	else{
		ps1->pTop=ps1->pBottom;
		ps1->pBottom->next=NULL;
		return;
	}
}

//判断栈是为空,空返回1,不空返回0
int Isempty(pStack ps1)
{
	if(ps1->pTop==ps1->pBottom)
		return 1;
	else return 0;
}

//压栈;
void Push(pStack ps1,int *pVal)
{
	pNode p;
	p=ps1->pTop;
	ps1->pTop=(pNode)malloc(sizeof(Node));
	ps1->pTop->data=*pVal;
	ps1->pTop->next=p;
	return;
}

//出栈,用val返回出栈元素值,成功返回1,失败返回0
int Pop(pStack ps1,int *pVal)
{
	pNode p;
	if(Isempty(ps1))
		return 0;
	else
	{
		p=ps1->pTop;
		*pVal=ps1->pTop->data;
		ps1->pTop=ps1->pTop->next;
		free(p);
		return 1;
	}
}

//get栈顶元素,用val返回,成功返回1,失败返回0
int Gettop(pStack ps1,int *pVal)
{
	if(Isempty(ps1))
		return 0;
	else
	{
		*pVal=ps1->pTop->data;
		return 1;
	}
}

//从栈顶遍历到栈底
void Traverse(pStack ps1)
{
	pNode p;
	if(Isempty(ps1))
		printf("栈为空!\n");
	else
	{
		printf("从栈顶遍历到栈底:");
		for(p=ps1->pTop;p!=ps1->pBottom;p=p->next)
			printf("%d ",p->data);
		printf("\n");
	}
}

你可能感兴趣的:((C语言)栈的链式存储结构的实现)