数据结构(C语言版)---第三章栈和队列 3.4.2 队列的链式表示和实现(单链表)
只是实现了简单的算法,了解队列的FIFO,源码如下:
#include <stdio.h> #include <stdlib.h> typedef int QElemType ; typedef short Status; typedef struct QNode { QElemType data; struct QNode * next; }QNode,*QueuePtr; typedef struct { QueuePtr front; QueuePtr rear; }LinkQueue; Status InitQueue(LinkQueue *Q) { Q->front = Q->rear = (QueuePtr)malloc(sizeof(QNode)); if(!Q->front) { exit(0); } //printf("init %p\n",Q->front); Q->front->next = NULL; } Status DestroyQueue(LinkQueue *Q) { while(Q->front) { Q->rear = Q->front->next; //printf("free : %p\n",Q->front); free(Q->front); Q->front = Q->rear; } return 1; } Status InsertQueue(LinkQueue *Q,QElemType e) { QueuePtr p = (QueuePtr)malloc(sizeof(QNode)); if(!p) { exit(0); } p->data = e; p->next = NULL; //printf("insert %p\n",p); Q->rear->next = p; Q->rear = p; return 1; } Status DeleteQueue(LinkQueue *Q, QElemType *e) { if(Q->front == Q->rear) { return -1; } QueuePtr p; p = Q->front->next; *e = p->data; Q->front->next = p->next; if(Q->rear == p) { Q->rear = Q->front; } //printf("del %p\n",p); free(p); return 1; } QElemType GetHead(LinkQueue *Q) { if(Q->front != Q->rear) { return Q->front->data; } return -1; } void PrintQueue(LinkQueue *Q) { QueuePtr p; p = Q->front->next; while(p) { printf("%p: %d\t",p,p->data); p = p->next; } printf("\n"); } int main(int argc, char** argv) { LinkQueue Q; InitQueue(&Q); int i = 0; printf("--------insert------\n"); for(i = 0 ; i < 8 ; i ++) { InsertQueue(&Q, i); } PrintQueue(&Q); printf("--------delete------\n"); DeleteQueue(&Q,&i); PrintQueue(&Q); DestroyQueue(&Q); return 1; }
运行结果如下:
root@ubuntu:/mnt/hgfs/E/Lessons/MyExercise/DS/3# ./LinkQueue --------insert------ 0x8803018: 0 0x8803028: 1 0x8803038: 2 0x8803048: 3 0x8803058: 4 0x8803068: 5 0x8803078: 6 0x8803088: 7 --------delete------ 0x8803028: 1 0x8803038: 2 0x8803048: 3 0x8803058: 4 0x8803068: 5 0x8803078: 6 0x8803088: 7 root@ubuntu:/mnt/hgfs/E/Lessons/MyExercise/DS/3#
至于离散事件模拟以后再看。