1、#includestdlib.hmalloc.h#define MAXNUM 100#define ElemType int #define TRUE 1#define FALSE 0 /定义队列的顺序存储结构typedef struct ElemType queueMAXNUM; int front; int rear;sqqueue;/初始化顺序队列int initQueue(sqqueue *q) if(!q)return FALSE; q-front=-1;rear=-1; return TRUE;/入队int append(sqqueue *q,ElemType x) if(q-re
2、ar=MAXNUM-1)return FALSE q-rear+; q-queueq-rear=x; return TRUE; /出队ElemType Delete(sqqueue *q) ElemType x; if(q-front=q-rear) printf(队列空!n);return 0; x=q-queue+q-front; printf(队头元素%d出队!,x); return x;/判断队列是否为空int Empty(sqqueue *q)if(q-rear)return TRUE;return FALSE; /获取队头元素int gethead(sqqueue *q) Elem
3、Type x;if(q-printf( x=q-front+1;printf(n队头元素:%d出队n /遍历队 void display(sqqueue *q) int s; s=q-front; printf(队列为空! elsen顺序队列依次为: while(s s=s+1;%dqueues);顺序队列队尾元素所在位置为:rear=%dn,q-rear);书序队列队头元素所在位置为:front=%dn,q-front); /建立顺序队列 void Setsqqueue(sqqueue *q) int n,i,m;n请输入顺序队列的长度: scanf(%d,&n);n请依次输入顺序队列的元素
4、值: for(i=0;in;i+) scanf(m); append(q,m); /主函数 void main() sqqueue *head; int x,select; head=(squeue*)malloc(sizeof(squeue); printf(n第一次使用必须初始化! do printf(n*主菜单*nn 1 初始化队列 nn 2 建立顺序队列 nn 3 入队 nn 4 出队 nn 5 判断队列是否为空 nn 6 取队头元素 nn 7 遍历队列 nn 0 退出程序 nn*nn请选择操作: scanf(select); switch(select) case 1: initQu
5、eue(head); printf(已经初始化队列! break; case 2: Setsqqueue(head) printf(n已经建立队列! dispaly(head); break; case 3: printf(请输入队的值: scanf(x); append(head,x); dispaly(head); case 4: Delete(head); diapaly(head); case 5: if(Empty(head) else队列非空! case 6: gethead(head); case 7: dispaly(head); case 0: exit(0); while(
6、selecttop= -1;/入栈void Push(SqStack *p,ElemType x) if(p-toptop=p-top+1; p-stackp-top=x;Overflow!/出栈ElemType Pop(SqStack *p) if(p-top=0) x=p-top;栈顶数据元素%d已经被删除!,p-top);top-1; return(x); printf(Underflow! return(0); /获取栈顶元素 ElemType GetTop(SqStack *p)n栈顶元素为:%dn /遍历顺序栈 void OutStack(SqStack *p) int i;0)这
7、是一个空栈! for(i=p-top;i=0;i-);第%d个数据元素为:%6dn,i,p-stacki); /置空顺序栈 void setEmpty(SqStack *p) p-top=-1; SqStack *q; int cord;ElemType a;第一次使用必须初始化!n 1 初始化顺序栈 nn 2 插入一个元素 nn 3 删除栈顶元素 nn 4 区栈顶元素 nn 5 置空顺序栈 nn 6 结束程序运行 n你选择的序号是(1,2,3,4,5,6)cord); switch(cord) q = (SqStack * )malloc(sizeof(SqStack); InitStack
8、(q); OutStack(q); break;请输入要插入的元素:a= scanf(a); Push(q,a); break; Pop(q); OutStack(q); GetTop(q); setEmpty(q);n顺序栈被置空! while(cord=6);运行结果1、初始化书序栈2、3、入栈及出栈4、出栈及取栈顶元素5、6、初始化队列并输入顺序队列7、插入新的队尾元素,即入队8、删除队头数据元素,即出队9、判断队列是否为空。10、取队列头元素。11、遍历顺序队列。实验总结 此次实验,初步学会了建立顺序栈与顺序队列,并学会了栈和队列的基本算法,再次巩固了指针的用法。巩固了在课本上学的知识,加深了对栈和队列的认识与掌握。不过,在编程时,发觉自己在定义结构体和变量时,还有很多不足。而且,在编写程序时,自己有点粗心大意,经常忘记加“;”和“”等。路漫漫其修远兮,还得上下而求索啊!
copyright@ 2008-2022 冰豆网网站版权所有
经营许可证编号:鄂ICP备2022015515号-1