mmmaxwell 2016-11-06 00:53 采纳率: 0%
浏览 866
已采纳

关于单链表实现队列的错误

下面是源代码:

 #include<stdio.h>
#include<stdlib.h>

typedef int ElemType;
struct QNode
{
    ElemType data;
    QNode* next;
};

struct Queue
{
     QNode* rear;
     QNode* front;
};

Queue* create()
{
    QNode* q;
    Queue* Q;
    q=new QNode;
    q->next=NULL;
    Q->front=Q->rear=q;
    return Q;
}

void EnQueue(Queue* Q,ElemType e)
{
    QNode* N;
    N=new QNode;
    N->next=NULL;
    N->data=e;
    Q->rear->next=N;
    Q->rear=N;
}

void DelQueue(Queue* Q)
{
    QNode* N;
    N=Q->front->next;
   Q->front->next=N->next;
    free(N);
}

void TraveQueue(Queue* Q)
{
    while(Q->front->next!=NULL){
        printf("%d",Q->front->next->data);
        Q->front->next=Q->front->next->next;
    }
}


int main()
{
    Queue* Q;
    Q=create();
    EnQueue(Q,5);
    EnQueue(Q,7);
    EnQueue(Q,9);
    TraveQueue(Q);
    DelQueue(Q);
    TraveQueue(Q);
}

单步调试的时候,无法删除元素,问题出在DelQueue函数里面,也就是Q->front->next=N->next求大神给予指导;

  • 写回答

2条回答 默认 最新

  • 小灸舞 2016-11-07 01:53
    关注

    两个问题:
    1.create函数里Q也需要分配空间,需要new
    2.DelQueue函数里应该用delete,而不是free
    3.你的TraveQueue函数,遍历的时候应该弄一个临时变量来遍历才行(你就是这里出错的!!!)

     #include<stdio.h>
    #include<stdlib.h>
    
    typedef int ElemType;
    struct QNode
    {
        ElemType data;
        QNode* next;
    };
    
    struct Queue
    {
        QNode* rear;
        QNode* front;
    };
    
    Queue* create()
    {
        QNode* q;
        Queue* Q = new Queue;
        q = new QNode;
        q->next = NULL;
        Q->front = Q->rear = q;
        return Q;
    }
    
    void EnQueue(Queue* Q, ElemType e)
    {
        QNode* N;
        N = new QNode;
        N->next = NULL;
        N->data = e;
        Q->rear->next = N;
        Q->rear = N;
    }
    
    void DelQueue(Queue* Q)
    {
        QNode* N;
        N = Q->front->next;
        Q->front->next = N->next;
        free(N);
    }
    
    void TraveQueue(Queue* Q)
    {
        QNode *temp = Q->front->next;
        while (temp != NULL){
            printf("%d ", temp->data);
            temp = temp->next; 
        }
        printf("\n");
    }
    
    
    int main()
    {
        Queue* Q;
        Q = create();
        EnQueue(Q, 5);
        EnQueue(Q, 7);
        EnQueue(Q, 9);
        TraveQueue(Q);
        DelQueue(Q);
        TraveQueue(Q);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度