欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C语言实现栈

程序员文章站 2022-05-26 20:10:40
...

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

进栈

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;
}