队列的链式存储代码实现
队列初始化、判断是否为空、入队尾插法、出队头部删除
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 75 76 77
| #include <stdio.h> #include <stdlib.h>
typedef int ElemType; typedef struct LinkNode { ElemType data; struct LinkNode* next; } LinkNode;
typedef struct { LinkNode *front, *rear; } LinkQueue;
void initQueue(LinkQueue &Q) { Q.front = Q.rear = (LinkNode*)malloc(sizeof(LinkNode)); Q.front->next = NULL; }
bool isEmpty(LinkQueue Q){ return (Q.front->next == NULL); }
void enQueue(LinkQueue &Q, ElemType e) { LinkNode* p = (LinkNode*)malloc(sizeof(LinkNode)); p->data = e; p->next = NULL; Q.rear->next = p; Q.rear = p; }
bool deQueue(LinkQueue &Q, ElemType &e) { if (Q.front == Q.rear) { return false; } LinkNode *p = Q.front->next; e = p->data; Q.front->next=p->next; if(Q.rear==p){ Q.rear=Q.front; } free(p); return true; }
int main() { LinkQueue Q; bool ret; initQueue(Q); ret = isEmpty(Q); if(ret){ printf("队列为空\n"); }else { printf("队列不为空\n"); } enQueue(Q, 2); enQueue(Q, 3); enQueue(Q, 4); enQueue(Q, 5); enQueue(Q, 6); ElemType e; ret = deQueue(Q,e); if (ret) { printf("出队元素:%d\n",e); }else{ printf("出队失败"); } return 0; }
|