只是实现了简单的算法,了解队列的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 ",Q->front); Q->front->next = NULL; } Status DestroyQueue(LinkQueue *Q) { while(Q->front) { Q->rear = Q->front->next; //printf("free : %p ",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 ",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 ",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 ",p,p->data); p = p->next; } printf(" "); } int main(int argc, char** argv) { LinkQueue Q; InitQueue(&Q); int i = 0; printf("--------insert------ "); for(i = 0 ; i < 8 ; i ++) { InsertQueue(&Q, i); } PrintQueue(&Q); printf("--------delete------ "); 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#
至于离散事件模拟以后再看。