数据结构C 语言描述——实现栈的基本功能

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

typedef char DataType ;
struct node;//定义一个结点
typedef struct node *PNode; //定义结点指针

struct node{
	DataType info;
	PNode next;
};

struct stack{//创建一个栈结构体
	PNode top;//指向栈顶元素
};

typedef struct stack *Pointstack;
Pointstack createEmpty_stack(void);//无返回值
int  ifEmpty_stack(Pointstack Pstack);//传入栈参数
void pushElement_stack(Pointstack pstack,DataType x);
void popElement_stack(Pointstack pstack,DataType x);
DataType ElementStackTop(Pointstack pstack);


//创建一个空栈,返回指向空栈的指针
Pointstack createEmpty_stack(){
	Pointstack Pstack=(Pointstack)malloc(sizeof(struct stack));//为结点申请空间
	if(Pstack!=NULL){
		Pstack->top=NULL;//栈顶赋值为空
	}
	else{
		printf("out of speac");
	}
	return Pstack;
}

//判断栈是否为空
int ifEmpty_stack(Pointstack pstack){
	return  (pstack->top?0:1);
}

//往栈中压入一个元素
void pushElement_stack(Pointstack pstack,DataType x){
	PNode Snode=(PNode)malloc(sizeof(struct node));//申请一个新的结点空间
	if (Snode==NULL)
	{
		printf("out of speac");
	} 
	else
	{
		Snode->info=x;
		Snode->next=pstack->top;
		pstack->top=Snode;
	}
	//printf("进栈成功\n");
}

//出栈。即删除一个元素
void popElement_stack(Pointstack pstack){
	if (ifEmpty_stack(pstack))//判断栈是否已空
	{
		printf("out of speac");
	} 
	else
	{
		PNode p=pstack->top;
		pstack->top=pstack->top->next;
		free(p);
	}

}

//求栈顶元素
DataType ElementStackTop(Pointstack pstack){
	if (ifEmpty_stack(pstack))
	{
		printf("stack is empty\n");
		exit(0);
	} 
	else
	{
		return pstack->top->info;
	}
}

void main(){
	int data;
	char ch;
	int top;
	Pointstack newstack=createEmpty_stack();
	printf("输入数字创建栈,以-1结束输入:\n");
	scanf("%d",&data);
	while(data!=-1){
		pushElement_stack(newstack,data);
		scanf("%d",&data);
	}
	printf("\n");
	while(!ifEmpty_stack(newstack)){
		top=ElementStackTop(newstack);
		printf("%d ",top);
		popElement_stack(newstack);
	}
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值