C语言链式队列实现 - 入队、出队、遍历操作
#include<stdio.h> #include<stdlib.h> #define null 0 #define elemtype int typedef struct qnode { elemtype data; struct qnode *next; }qnodetype; typedef struct { qnodetype *front; qnodetype *rear; }lqueue;
//入链队列 void lappend(lqueue *q,int x) { qnodetype *p; p=(qnodetype *)malloc(sizeof(qnodetype)); p->data=x; p->next=null; q->rear->next=p; q->rear=p; }
//初始化并建立链队列
void creat(lqueue *q) { qnodetype *h; int i,n,x; printf('输入将建立链队列元素的个数:n='); scanf('%d',&n); h=(qnodetype *)malloc(sizeof(qnodetype)); h->next =null; q->front=h; q->rear=h; for(i=1;i<=n;i++) { printf('链队列第 %d 个元素的值为:',i); scanf('%d',&x); lappend(q,x); } }
//出链队列 elemtype ldelete(lqueue *q) { qnodetype *p; elemtype x; if(q->front==q->rear) { printf('队列为空! '); exit(0); } p=q->front ->next ; q->front->next=p->next ; x=p->data; if(q->rear==p) { q->rear=q->front; } free(p); return x; }
//遍历链队列 void display(lqueue *q) { qnodetype *p; p=q->front ->next ; printf(' 链队列元素依次为:'); while(p!=null) { printf('%d-->',p->data ); p=p->next ; } printf('
遍历链队列结束! '); }
//主函数 void main() { lqueue p; int x,cord; printf(' 第一次操作请选择初始化并建立链队列!* '); do { printf(' 链队列的基本操作!
');
printf('=======================
');
printf(' 主菜单:
');
printf('=======================
');
printf('
1 初始化并建立链队列
');
printf('
2 入链队列
');
printf('
3 出链队列
');
printf('
4 遍历链队列
');
printf('
5 结束程序运行
');
printf('
'); scanf('%d',&cord); switch(cord) { case 1: { p=(lqueue *)malloc(sizeof(lqueue)); creat(p); display(p); }break; case 2: { printf('请输入队列元素的值:x='); scanf('%d',&x); lappend(p,x); display(p); }break; case 3: { printf('出链队列元素:x=%d ',ldelete(p)); display(p); }break; case 4: { display(p); }break; case 5: exit(0); } }while(cord<=5);
原文地址: https://www.cveoy.top/t/topic/mAmt 著作权归作者所有。请勿转载和采集!