C语言实现栈

第一次自己实现栈,有一些激动呢!!!

进栈

 

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

typedef struct node{
	int elem;
	struct node *next;
}DataNode;

typedef struct {
	int count;
	DataNode *next;
}*LinkHead,Linkstack;

int Init(LinkHead *S)
{
	LinkHead p=(LinkHead)malloc(sizeof(Linkstack));
	p->next = NULL;
	p->count = 0;
	(*S) = p;
	return 0;
}

int EnStack(LinkHead *S,int elem)
{
	DataNode *p = (DataNode *)malloc(sizeof(DataNode));
	p->elem = elem;
	p->next = (*S)->next;
	(*S)->next = p;
	(*S)->count += 1;
	
	return 0;
}
int DeStack(LinkHead *S,int *elem){
	if(*S==NULL)
	{
		return -1;
	}
	DataNode *p=(*S)->next;
	*elem = p->elem;
	(*S)->next = p->next;
	free(p);
	(*S)->count -= 1;
	return 0;
}
int Clear(LinkHead *S)
{
	while((*S)->next!=NULL)
	{
		DataNode *p=(DataNode *)malloc(sizeof(DataNode));
		p = (*S)->next;
		(*S)->next = p->next ;
		free(p);
		(*S)->count -= 1;
	}
	(*S)->next = NULL;
	(*S)->count = 0;
	return 0;
}
int Destory(LinkHead *S)
{
	Clear(S);
	free(*S);
	(*S)=NULL;
	return 0;
}
int Traverse(LinkHead S)
{
	DataNode *p=S->next ;
	
	for(int i=0;i<S->count;i++)
	{
		printf("%d ",p->elem);
		p=p->next;
	}
	return 0;
}

int main()
{
	LinkHead S;
	Init(&S);
	int n;
	scanf("%d",&n);
	for(int i=0;i<n;i++){
		int m;
		scanf("%d",&m);
		EnStack(&S,m);
	}
	Traverse(S);
	int elem;
	DeStack(&S,&elem);
	printf("\n%d\n",elem);
	DeStack(&S,&elem);
	printf("\n%d\n",elem);	
	Traverse(S);
	Clear(&S);
	printf("\n");
	Traverse(S);
	printf("\n");
	 
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值