您的位置:首页 > 理论基础 > 数据结构算法

数据结构顺序栈的各种操作

2013-05-21 18:46 302 查看
/** 
    头文件stu.h 
    @jeasn168 
*/  
#include<stdio.h>  
#include<string.h>  
#define MaxS 50  
typedef struct  
{  
    char name[MaxS];  
    char stuno[MaxS];  
    float score;  
}stu;  
//输出stu  
void DispStu(const stu &s)  
{  
    printf("Name:%s\n",s.name);  
    printf("StuNo:%s\n",s.stuno);  
    printf("Score:%f\n",s.score);  
}  
   
   
//比较stu类型  
int isEqual(const stu &a,const stu &b)  
{  
    if(strcmp(a.name,b.name)==0&&strcmp(a.stuno,b.stuno)==0&&a.score==b.score)  
        return 1;  
    else  
        return 0;  
}  
   

/**
	顺序栈的各种操作
	@jeasn168
*/
#include<stdio.h>
#include<malloc.h>
#include"stu.h"
#define MaxSize 1000
typedef stu ElemType;
//定义顺序栈结构
typedef struct
{
	ElemType data[MaxSize];
	int top;
}SqStack;

//初始化栈
void InitStack(SqStack *&s)
{
	s=(SqStack *)malloc(sizeof(SqStack));
	s->top=-1;
	printf("初始化栈!\n");
}

//销毁栈
void DestroyStack(SqStack *&s)
{
	free(s);
	printf("栈已销毁!\n");
}

//判断栈是否为空
int StackEmpty(SqStack *s)
{
	return(s->top==-1);
}

//进栈
int Push(SqStack *&s,const ElemType &e)
{
	if(s->top==MaxSize-1)
	{
		return 0;
		printf("栈已满!\n");
	}
	s->top++;
	s->data[s->top]=e;
	return 1;

}

//出栈
int Pop(SqStack *&s,ElemType &e)
{
	if(StackEmpty(s))
	{
		printf("栈已为空!\n");
		return 0;
	}
	e=s->data[s->top];
	s->top--;
	return 1;
}

//从栈顶向下输出栈内容
void DispStack(SqStack *s)
{
	int i=s->top;
	for(;i>-1;i--)
	{
		//printf("%c\n",s->data[i]);
		DispStu(s->data[i]);
	}
	printf("\n");
}

//从栈底向上输出栈内容
void DispStackR(SqStack *s)
{
	int i=0;
	for(;i<=s->top;i++)
	{
		//printf("%c\n",s->data[i]);
		DispStu(s->data[i]);
	}
	printf("\n");
}
int main()
{
	stu student[5]={{"Li","S12101",85},{"Liu","S12102",92.5},{"Wang","S12103",54},{"Huang","S12104",76},{"John","S12105",78}};
	stu st1={"LiLy","S12108",85},st2;
	SqStack *stuStack;
	int i=0;
	int t=sizeof(student)/sizeof(stu);
	printf("%d\n",t);
	InitStack(stuStack);//必须先初始化!
	for(i=0;i<t;i++)
	{
		Push(stuStack,student[i]);//入栈
	}
	printf("栈顶向下输出:\n");
	DispStack(stuStack);//栈顶向下
	printf("栈低向上输出:\n");
	DispStackR(stuStack);//栈低向上

	Pop(stuStack,st2);//出栈一个元素
	printf("出栈一个元素:\n");
	DispStu(st2);//输出出栈元素
	printf("出栈之后输出栈:\n");
	DispStack(stuStack);//出栈之后输出栈
	DestroyStack(stuStack);
	return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: