【问题标题】:How to add element to queue如何将元素添加到队列
【发布时间】:2016-12-11 13:02:35
【问题描述】:

我真的不明白我的代码有什么问题。

当我添加第一个元素时一切都很好,但在那之后,它就不起作用了。当 ptr 为 NULL 时,它进入 while 循环。 检查是否为null有问题吗?

struct Car
{
    int startTime;
    char *model;
    char *code;
    char *location;
    struct Car *next;
    int deptEnterTime;
    bool waitingForFraming;
    bool waitingForPainting;
    bool waitingForPolishing;
    bool waitingForEngine;
    bool waitingForElectronic;
    bool waitingForIndoor;
    bool waitingForTest;
};

struct Car *head = NULL;
void insert(int startTime, char *model, char *code)
{
    /*create a link*/
    struct Car *link = (struct Car*) malloc(sizeof(struct Car));

    link->startTime= startTime;
    link->model = model;
    link->code = code;
    link->waitingForFraming=true;
    link->waitingForPainting=false;
    link->waitingForPolishing=false;
    link->waitingForEngine=false;
    link->waitingForElectronic=false;
    link->waitingForIndoor=false;
    link->waitingForTest=false;

    if(head == NULL)
    {
        head = link;
    }
    else
    {
        struct Car *ptr;
        ptr = head->next;

        while(ptr != NULL)
        {
            ptr = ptr->next;
        }
        ptr = link;

    } 
}

【问题讨论】:

    标签: c queue


    【解决方案1】:

    对于初学者,您必须为添加的元素将数据成员 next 设置为 NULL。

    struct Car *link = (struct Car*) malloc(sizeof(struct Car));
    
    link->next = NULL;
    //...
    

    这部分函数也是错误的

    else
    {
        struct Car *ptr;
        ptr = head->next;
    
        while(ptr != NULL)
        {
            ptr = ptr->next;
        }
        ptr = link;
    
    } 
    

    应该这样写

    else
    {
        struct Car *ptr = head;
    
        while( ptr->next != NULL)
        {
            ptr = ptr->next;
        }
        ptr->next = link;
    
    } 
    

    请注意,如果您要将元素添加到列表的末尾,那么您应该至少声明一个双面列表。否则将元素添加到列表末尾是低效的。

    【讨论】:

      【解决方案2】:

      你应该把它分配给最后一个可用的结构而不是下一个,你可以这样做:

      struct Car *ptr = head;
      while(ptr->next != NULL)
      {
          ptr = ptr->next;
      }
      ptr->next = link;
      

      我建议将 link->next 设置为 NULL 以避免出现随机数据:

      ....
      link->waitingForTest=false;
      link->next=NULL;
      
      if(head == NULL)
      .....
      

      【讨论】:

        猜你喜欢
        • 2017-04-09
        • 2018-07-29
        • 1970-01-01
        • 2015-08-01
        • 1970-01-01
        • 1970-01-01
        • 2014-06-16
        相关资源
        最近更新 更多