链栈的基本操作

1.带头结点:

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

#define ElemType int
//基本数据类型:
typedef struct LinkNode{
	ElemType data;
	struct LinkNode* next;
}LinkNode,*LinkStack;

//初始化链栈:
bool InitLinkStack(LinkStack &S)
{
	S=(LinkStack)malloc(sizeof(LinkNode));
	S->next=NULL;
	return true;
} 

//判断链栈是否为空栈:
bool LinkStackEmpty(LinkStack S)
{
	if(S->next)return false;
	else return true;
}

//链栈的入栈操作:
bool Push(LinkStack &S,ElemType x)
{
	if(x!=9999)
	{
	   LinkNode *r=(LinkNode*)malloc(sizeof(LinkNode));
	   r->data=x;
	   r->next=S->next;
	   S->next=r;
	   return true;
	}
	else return false;
}

//获取链栈的栈顶元素,但不做出栈操作 
bool GetTop(LinkStack S,ElemType &x)
{
	if(S->next==NULL)return false;
	x=S->next->data;
	return true;
}

//链栈的出栈操作 
bool Pop(LinkStack &S,ElemType &x)
{
	LinkNode *p;
	if(S->next==NULL)return false;
	p=S->next;
	x=p->data;
	S->next=p->next;
	free(p);
	return true;
}

int main()
{
	ElemType x;
	//声明一个链栈: 
	LinkStack S;
    //链栈初始化:
	InitLinkStack(S);
	
	if(LinkStackEmpty(S))printf("\n此链栈是空的\n");
	else printf("\n此链栈不空\n");
	
	printf("\n开始向链栈中输入数据:\n");
	while(1)
	{
		scanf("%d",&x);
		if(x==9999)
		{
			printf("\n输入结束\n");
			break;
		}
		if(Push(S,x))printf("\n成功插入\n");
	}
	
	if(GetTop(S,x))printf("\n栈顶元素为: %d\n",x);
	
	printf("\n元素依次出栈:\n");
    while(Pop(S,x))printf("%d ",x);
	printf("\n");
}

2.不带头结点:

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

#define ElemType int
//基本数据类型:
typedef struct LinkNode{
	ElemType data;
	struct LinkNode* next;
}LinkNode,*LinkStack;

//初始化链栈:
bool InitLinkStack(LinkStack &S)
{
	S=NULL;
	return true;
} 

//判断链栈是否为空栈:
bool LinkStackEmpty(LinkStack S)
{
	if(S)return false;
	else return true;
}

//链栈的入栈操作:
bool Push(LinkStack &S,ElemType x)
{
	if(x!=9999)
	{
	   LinkNode *r=(LinkNode*)malloc(sizeof(LinkNode));
	   r->data=x;
	   r->next=S;
	   S=r;
	   return true;
	}
	else return false;
}

//获取链栈的栈顶元素,但不做出栈操作 
bool GetTop(LinkStack S,ElemType &x)
{
	if(S==NULL)return false;
	x=S->data;
	return true;
}

//链栈的出栈操作 
bool Pop(LinkStack &S,ElemType &x)
{
	LinkNode *p;
	if(S==NULL)return false;
	p=S;
	x=p->data;
	S=p->next;
	free(p);
	return true;
}

int main()
{
	ElemType x;
	//声明一个链栈: 
	LinkStack S;
    //链栈初始化:
	InitLinkStack(S);
	
	if(LinkStackEmpty(S))printf("\n此链栈是空的\n");
	else printf("\n此链栈不空\n");
	
	printf("\n开始向链栈中输入数据:\n");
	while(1)
	{
		scanf("%d",&x);
		if(x==9999)
		{
			printf("\n输入结束\n");
			break;
		}
		if(Push(S,x))printf("\n成功插入\n");
	}
	
	if(GetTop(S,x))printf("\n栈顶元素为: %d\n",x);
	
	printf("\n元素依次出栈:\n");
    while(Pop(S,x))printf("%d ",x);
	printf("\n");
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值