严蔚敏 吴伟明 数据结构 C链队列实现
#include<stdio.h>#include<stdlib.h>
#include<malloc.h>
/*jiang*/
typedef struct qnode{
int data;
struct qnode *next;
}qnode,*queueptr;
typedef struct{
queueptr front;
queueptr rear;
}linkqueue;
void initqueue(linkqueue *q){
q->front=q->rear=(queueptr)malloc(sizeof(qnode));
if(!q->front) exit(-2);
q->front->next=NULL;
}
void destroyqueue(linkqueue *q){
while(q->front){
q->rear=q->front->next;
free(q->front);
q->front=q->rear;
}
}
void clearqueue(linkqueue *q){
queueptr p,r;
q->rear=q->front;
p=q->front->next;
q->front->next=NULL;
while(p){
r=p;
p=p->next;
free(r);
}
}
int queueempty(linkqueue q){
if(q.front==q.rear) return 1;
else return 0;
}
int queuelength(linkqueue q){
queueptr p;
int i=0;
p=q.front;
while(p!=q.rear){
i++;
p=p->next;
}
return i;
}
void gethead(linkqueue q,int *e){
queueptr p;
if(q.front==q.rear) return;
p=q.front->next;
*e=p->data;
}
void enqueue(linkqueue *q,int e){
queueptr p;
p=(queueptr)malloc(sizeof(qnode));
if(!q) exit(-2);
p->data=e;
p->next=NULL;
q->rear->next=p;
q->rear=p;
}
void dequeue(linkqueue *q,int *e){
queueptr p;
if(q->front==q->rear) return;
p=q->front->next;
*e=p->data;
q->front->next=p->next;
if(p==q->rear) q->rear=q->front;
free(p);
}
void queuetraverse(linkqueue q){
queueptr p;
p=q.front->next;
printf("----------------------\n");
printf("data in queue:");
while(p){
printf("%2d",p->data);
p=p->next;
}
printf("\n");
printf("----------------------\n");
}
main(){
linkqueue q;
int i,e;
initqueue(&q);
printf("empty or not?(true:1,false :0)%2d\n",queueempty(q));
for(i=0;i<7;i++){
enqueue(&q,i);
}
queuetraverse(q);
printf("empty or not?(true:1,false :0)%2d\n",queueempty(q));
printf("insert data e:");
scanf("%d",&e);
enqueue(&q,e);
queuetraverse(q);
printf("length of queue:%2d\n",queuelength(q));
printf("after delete data:");
dequeue(&q,&e);
printf("the delete num:%2d\n",e);
queuetraverse(q);
gethead(q,&e);
printf("data of head qnode :%2d\n",e);
printf("after clear:\n");
clearqueue(&q);
printf("empty or not?(true:1,false :0)%2d\n",queueempty(q));
printf("length of queue:%2d\n",queuelength(q));
destroyqueue(&q);
}