链式队列一种实现

来源:互联网 发布:关于交通事故的数据 编辑:程序博客网 时间:2024/05/30 23:54

Queue有两种实现方式:数组和链表,本文属于链表实现方式,具体代码如下:

#include <stdio.h>#include <stdlib.h>typedef char element;typedef struct ListQueue {element data;struct ListQueue *next;}ListQueueNode, *ListQueueptr;typedef struct ptrListQueue {ListQueueptr front,rear;}ptrListQueueNode;void creatptrListQueue(ptrListQueueNode **q){*q = (ptrListQueueNode *)malloc(sizeof(ptrListQueueNode));if(NULL == *q){printf("Error: there is no memory to alloc\n");return;}(*q)->front = (*q)->rear = NULL;}int insertQueue(ptrListQueueNode *q, element e){ListQueueptr tmp=NULL;if(q->front == NULL){tmp=(struct ListQueue *)malloc(sizeof(ListQueueNode));         if(NULL == tmp)          {                  printf("Error: there is no memory to alloc\n");                  return -1;          }           tmp->data = e;          tmp->next = NULL;           q->rear = q->front = tmp;}else{tmp=(struct ListQueue *)malloc(sizeof(ListQueueNode));if(NULL == tmp)        {                printf("Error: there is no memory to alloc\n");                return -1;}tmp->data = e;tmp->next = NULL;q->rear->next = tmp;q->rear = tmp;}return 0;}int deleteQueue(ptrListQueueNode *q, element *e){ListQueueptr tmp=NULL;if(NULL == q->front){printf("Error: this queue is already empty\n");return -1;}else if(q->front->next == q->rear){tmp = q->rear;*e = tmp->data;free(tmp);q->rear = q->front;q->front->next = NULL;}else{tmp = q->front;*e = tmp->data;free(tmp);q->front = q->front->next;}return 0;}void printQueue(ptrListQueueNode *q){ListQueueptr tmp=q->front;if(q->front != NULL){while(tmp != NULL){printf("%c ",tmp->data);tmp = tmp->next;}printf("\n");}elseprintf("this is a empty queue\n");}int main(void){ptrListQueueNode *s;element e;int ret;creatptrListQueue(&s);scanf("%c",&e);while(e != '#'){if(e != ' ')insertQueue(s,e);scanf("%c",&e);}printQueue(s);ret = deleteQueue(s,&e);if(ret){printf("Error: occur error when delete the element of the listqueue\n");return -1;}printf("e = %c\n",e);printQueue(s);ret = deleteQueue(s,&e);if(ret){printf("Error: occur error when delete the element of the listqueue\n");return -1;}        printf("e = %c\n",e);        printQueue(s);ret = deleteQueue(s,&e);if(ret){printf("Error: occur error when delete the element of the listqueue\n");return -1;}        printf("e = %c\n",e);        printQueue(s);return 0;}