2>完成链队的剩下操作:出队、长度、销毁的功能函数的封装。
// 入队操作 void enqueue(Queue* q, int value) { Node* newNode = (Node*)malloc(sizeof(Node)); if (newNode == NULL) { printf("内存分配失败,无法入队。\n"); return; } newNode->data = value; newNode->next = NULL; if (isEmpty(q)) { q->front = newNode; q->rear = newNode; } else { q->rear->next = newNode; q->rear = newNode; } q->rear->next = q->front; // 形成循环 q->size++; } // 出队操作 void dequeue(Queue* q) { if (isEmpty(q)) { printf("队列为空,无法出队。\n"); return; } Node* temp = q->front; if (q->front == q->rear) { q->front = NULL; q->rear = NULL; } else { q->front = q->front->next; q->rear->next = q->front; // 更新循环链接 } free(temp); q->size--; } // 遍历队列 void traverseQueue(Queue* q) { if (isEmpty(q)) { printf("队列为空,无元素可遍历。\n"); return; } Node* current = q->front; do { printf("%d ", current->data); current = current->next; } while (current != q->front); printf("\n"); } // 获取队列长度 int getQueueSize(Queue* q) { return q->size; } // 销毁队列 void destroyQueue(Queue* q) { while (!isEmpty(q)) { dequeue(q); } }
作业7.10
最新推荐文章于 2024-09-10 10:21:38 发布