基于链表实现C语言队列出现异常输出,求排查解决
C语言链表队列实现的问题分析与修正
核心问题总结
你实现的队列出现异常输出,根源是入队、出队的核心逻辑完全违背了队列FIFO(先进先出)的特性,同时存在输出格式和内存释放的小问题。
具体问题与修正方案
1. 入队(enqueue)逻辑颠倒
队列要求新元素从队尾加入,但你的代码把新节点挂到了pBack(原队首)的前面,相当于把新元素放到了队首,完全搞反了顺序。
- 错误代码片段:
p->next = q->pBack; q->pBack = p; - 修正后:
q->pBack->next = p; q->pBack = p;
2. 出队(dequeue)逻辑错误
出队应该移除队首(pFront指向的节点),但你的代码却在遍历寻找pFront的前驱节点,然后修改pFront为该节点——这相当于删除了队尾元素,完全不符合队列规则。
- 修正逻辑:保存队首节点,更新
pFront为下一个节点,若队列变空则同步更新pBack,最后释放原队首节点。
3. 输出格式问题
你在输出出队结果时,printf的%d后没有加空格,导致返回值(1)和队列输出连在一起,出现110 20的异常。
- 修正代码:
printf("\nAfter removing front item: %d ", dequeue(q));
4. 内存释放不完整
原freeMemory函数没有释放队列结构体本身的内存,修正后需要在释放所有节点后调用free(q)。
修正后的完整代码
// C program to implement linked list queue #include <stdio.h> #include <stdlib.h> // Define a queue using linked list typedef struct _Node { int data; struct _Node *next; } Node; typedef struct _Queue { Node *pFront, *pBack; int size; } Queue; // Initialize queue Queue *init(void) { Queue *q = malloc(sizeof(*q)); if (q) { q->size = 0; q->pFront = q->pBack = NULL; } return q; } // Check if queue is empty int isEmpty(Queue *q) { return (q->pFront == NULL); } // Length of queue int Length(Queue *q) { return q->size; } // Add new item (队尾添加,符合FIFO) void enqueue(Queue *q, int val) { Node *p = malloc(sizeof(Node)); p->data = val; p->next = NULL; if (isEmpty(q)) { q->pFront = q->pBack = p; } else { q->pBack->next = p; q->pBack = p; } q->size++; } // Remove item (移除队首,符合FIFO) int dequeue(Queue *q) { if (isEmpty(q)) return 0; Node *temp = q->pFront; q->pFront = q->pFront->next; if (q->pFront == NULL) { q->pBack = NULL; } free(temp); q->size--; return 1; } // Display queue (从队首到队尾输出) void display(Queue *q) { Node *p = q->pFront; while (p != NULL) { printf("%d\t", p->data); p = p->next; } } // Free all memory used by the queue void freeMemory(Queue *q) { Node *p = q->pFront; Node *next; while (p != NULL) { next = p->next; free(p); p = next; } free(q); } int main() { Queue *q = init(); if (q) { enqueue(q, 10); enqueue(q, 20); enqueue(q, 30); printf("Queue:\n"); display(q); printf("\nAfter removing front item: %d ", dequeue(q)); display(q); printf("\nLength of the queue after all modification: %d", Length(q)); freeMemory(q); return 0; } return 1; }
修正后的输出
Queue: 10 20 30 After removing front item: 1 20 30 Length of the queue after all modification: 2
内容的提问来源于stack exchange,提问作者ahnherin092
相关产品推荐
相关产品推荐

