1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
| #include<stdio.h> #include<stdlib.h> #include<stdbool.h> typedef struct LinkNode { int data; LinkNode* next; }LinkNode; typedef struct{ LinkNode* front,*rear; }LinkQueue;
bool InitQueue(LinkQueue *Q) { Q->front=Q->rear=(LinkNode *)malloc(sizeof(LinkNode)); if (Q->front==NULL) { return false; } Q->front->next=NULL; return true; }
bool QueueEmpty(LinkQueue* Q) { return Q->front==Q->rear; }
bool EnQueue(LinkQueue* Q,int data) { LinkNode* s = (LinkNode*)malloc(sizeof(LinkNode)); if (s == NULL) { return false; } s->next= NULL; s->data = data; Q->rear->next = s; Q->rear = s; return true; }
bool DeQueue(LinkQueue* Q, int* a) { if (QueueEmpty(Q)) { return false; } *a = Q->front->next->data; LinkNode *p=Q->front->next; Q->front->next=p->next; if (Q->rear == p) { Q->rear=Q->front; } free(p); return true; } int main() { LinkQueue Q; if (InitQueue(&Q)) { printf("Queue initialized successfully.\n"); } else { printf("Failed to initialize queue.\n"); return -1; }
EnQueue(&Q, 1); EnQueue(&Q, 2); EnQueue(&Q, 3);
int data; while (DeQueue(&Q, &data)) { printf("Dequeued element: %d\n", data); }
return 0; }
|