实验目的
1、掌握栈、队列的逻辑结构、存储结构及基本操作;
2、针对计算机领域复杂工程问题,能够综合运用数据结构的基本理论和设计方法,设计出合理的算法。
实验内容
假设所贴脸谱的颜色顺序是白色、黄色、黑色、红色、青色、金色、银色,请用所学知识输出扯脸的序列。
请设计程序生成六十甲子。
提示:创建两个循环队列,一个循环队列用于存放十天干,一个循环队列用于存放十二地支,若天干队列为空,则让十天干入队列;若地支队列为空,则让十二地支依次入队列;若两个队都不为空时,两个队列各取一个元素出队列,并在屏幕上输出配对的天干地支;直到输出六十个甲子,程序结束。
第一题:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define MAXSIZE 10
typedef struct lianpu ElementType;
struct lianpu{
char color[6];
int num;
};
typedef struct SNode* PtrToSNode;
struct SNode{
ElementType *Data;
int top;
int MaxSize;
};
typedef PtrToSNode Stack;
Stack CreateStack(int Maxsize){
Stack S=(Stack)malloc(sizeof(struct SNode));
S->Data=(ElementType*)malloc(Maxsize*sizeof(ElementType));
S->top=-1;
S->MaxSize=Maxsize;
return S;
}
bool IsFull(Stack S){
return (S->top==S->MaxSize-1);
}
bool Push(Stack S,ElementType X){
if(IsFull(S)){
printf("堆栈满");
return false;
}else {
S->Data[++(S->top)]=X;
return true;
}
}
bool IsEmpty(Stack S){
return (S->top==-1);
}
ElementType Pop(Stack S){
if(IsEmpty(S)){
printf("堆栈空");
}else return (S->Data[(S->top)--]);
}
int main(){
Stack S;
int i;
char color[8][10]={"1","白色","黄色","黑色","红色","青色","金色","银色"};
S=CreateStack(MAXSIZE);
ElementType X;
for(int i=1;i<=7;i++){
X.num=i;
strcpy(X.color,color[i]);
Push(S,X);
}
printf("扯脸顺序依次为:\n");
for(i=1;i<=7;i++){
X=Pop(S);
printf("%2d%s\n",X.num,X.color);
}
return 0;
}
第二题:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<math.h>
#define MAXSIZE 60
typedef struct tgdz ElementType;
struct tgdz{
char a[4];
};
typedef struct QNode *PtrToNode;
struct QNode{
ElementType *Data;//存储元素的数组
int Front,Rear;//队列的头尾指针
int MaxSize;//队列最大容量
};
typedef PtrToNode Queue;
bool tg(Queue Q);
bool dz(Queue Q);
Queue CreateQueue(int MaxSize){
Queue Q=(Queue)malloc(sizeof(struct QNode));
Q->Data=(ElementType*)malloc(MaxSize*sizeof(ElementType));
Q->MaxSize=MaxSize;
Q->Front=Q->Rear=0;
return Q;
}
//判断队列是否为满
bool IsFull(Queue Q){
return ((Q->Rear+1)%Q->MaxSize==Q->Front);
}
//入队
bool AddQ(Queue Q,ElementType X){
if(IsFull(Q)){
printf("队满");
return false;
}else{
Q->Rear=(Q->Rear+1)%Q->MaxSize;
Q->Data[Q->Rear]=X;
return true;
}
}
//判断队是否为空
bool IsEmpty(Queue Q){
return (Q->Front==Q->Rear);
}
ElementType DeleteQ(Queue Q){
if(IsEmpty(Q)){
printf("队列空");
}else {
Q->Front=(Q->Front+1)%Q->MaxSize;
return Q->Data[Q->Front];
}
}
bool tg(Queue Q){
ElementType X;
int i;
char tg[10][4]={"甲","乙","丙","丁","戊","己","庚","辛","任","癸"};
for(i=0;i<10;i++){
strcpy(X.a,tg[i]);
AddQ(Q,X);
}
}
bool dz(Queue Q){
ElementType X;
int i;
char dz[12][4]={"子","丑","寅","卯","辰","巳","午","未","申","酉","戌","亥"};
for(i=0;i<12;i++){
strcpy(X.a,dz[i]);
AddQ(Q,X);
}
return true;
}
int main(){
Queue Q,E;
Q=CreateQueue(11);
E=CreateQueue(13);
ElementType X;
tg(Q);
dz(E);
printf("60甲子为:\n\n");
for(int i=1;i<=60;i++){
printf("%02d%s%s\t",i,DeleteQ(Q).a,DeleteQ(E).a);
if(IsEmpty(Q))
tg(Q);
if(IsEmpty(E))
dz(E);
if(i%10==0)
printf("\n");
}
return 0;
}