C语言实现的链栈

C语言实现的链栈,包括基本操作:
代码:

#include<stdio.h>
#include<stdlib.h>
//链栈
typedef struct student
{
	char name[10];
	int age;
 }Student;
// typedef student Student;
typedef struct stackNode
{
	Student data;
	struct Stack *next;
}StackNode;

typedef struct Stack
{
	StackNode *top;
	int length;
}Stack;

//初始化
void InitStack(Stack *S)
{
    S->top=NULL;
    S->length=0;
	printf("初始化成功!
");
	return;
 } 
 
 //入栈
 void Push(Stack *S,Student stu)
 {
    StackNode *s=(StackNode*)malloc(sizeof(StackNode));
 	if (!s)
 	{
 		printf("入栈开辟空间失败!
");
 		exit(1);
	}
	s->data=stu;
	s->next=S->top;
	S->top=s; 
	S->length++; 
	printf("入栈成功!
");
	printf("栈长:%d
",S->length);
	return;
	
  } 
  
  //栈长
  int LengthStack(Stack *S)
  {
  	return S->length;
   } 
  
  //出栈 
  Student Pop(Stack *S)
  {
  	StackNode *p;
  	Student stu;
  	if (S->top==NULL)
  	{
  		printf("栈为空!
");
  		exit(1);
	}
	stu=S->top->data;
	p=S->top;
	S->top=p->next;
	free(p);
	S->length--;
	printf("出栈成功!
");
	return stu;
  }
  
  //判断栈空
  int StackEmpty(Stack *S)
  {
  	if (S->top==NULL)
  	{
  		printf("栈为空!
");
	  }
	  return 0;
   } 
  void main()
  {
  	int i;
  	Stack S,*p;
  	p=&S;
  	Student stu,stu1;
  	InitStack(&S);
  	//Push2个元素 
  	for(i=0;i<2;i++)
  	{
  		printf("请输入学生的name和age:
");
  	    scanf("%s%d",&stu.name,&stu.age);
  	    Push(&S,stu);
	}
	
	// Pop全部元素
	while (p->length!=0)
	{
		stu1=Pop(&S);
		printf("学生的name:%s ,age: %d
",stu1.name,stu1.age);
	 } 
  	//判断栈空
	  StackEmpty(&S); 
  }
原文地址:https://www.cnblogs.com/glory-yl/p/14667357.html