voidEnQueue(LinkQueue* lq) { int e; QueuePtr p = (QueuePtr)malloc(sizeof(QueuePtr)); // Pay attention to the difference of assigning and pointing. if (!p) { printf("OVERFLOW!"); } else { printf("Input the number you want to insert:\n"); scanf_s("%d", &e); p->data = e; p->next = NULL; lq->rear->next = p; lq->rear = p; printf("Insert successfully.\n"); } }
voidDeQueue(LinkQueue* lq) { int e; QueuePtr p; if (lq->front == lq->rear) { printf("ERROR"); } p = lq->front->next; e = p->data; lq->front->next = p->next; printf("%d is deleted.\n", e); if (p == lq->rear) { lq->rear = lq->front; // Change pointer rear when rear is deleted. } }
自定义show函数方便观察与调试:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
voidShowQueue(LinkQueue* lq) { QueuePtr p; if (lq->front == lq->rear) { printf("Queue is empty.\n"); } else {
p = lq->front->next; while (p->next) { printf("Order: %d\n", p->data); p = p->next; } printf("Order: %d\n", p->data); } }
销毁函数:(在这里关于无法free花费了大量的时间,解决的方法与思考放在第二部分)
1 2 3 4 5 6 7 8 9 10 11 12 13
voidDestoryQueue(LinkQueue* lq) { QueuePtr p; // Q3: When should I spare space for it? A3: When it has something spared to assign. p = lq->front->next; while (p) { QueuePtr q; // Here p and q are oringinally in form of "()malloc(size())", but they actually don't have to. q = p; p = q->next; free(q); } printf("Destoried.\n"); }