在链表C中无限循环

时间:2012-12-14 09:54:35

标签: c pointers while-loop structure

我遇到了一个问题,我想将项目添加到链接列表的末尾,但似乎我在这里陷入无限循环。

void addCheckPoint(struct checkPoints **checkPoint) {
    struct checkPoints *checkPt = *checkPoint;

    while (checkPt->next != NULL) {
        checkPt->next;
        if (checkPt->next == NULL) {
            scanf("%c %d %d %d %d", &checkPt->dropOut, &checkPt->currentPoint, &checkPt->competitor, &checkPt->hour, &checkPt->minute);
        }
    }
}

4 个答案:

答案 0 :(得分:3)

您永远不会更新循环中checkPt的值。改变行

checkPt->next;

checkPt = checkPt->next;

解决这个问题。

请注意,此功能可能还有其他问题。尽管它的名字,它实际上并没有添加任何东西到列表中。它改为编辑尾部项目的内容。如果这不是故意的,你需要malloc一个新元素,然后将它添加到尾部。

答案 1 :(得分:2)

void addCheckPoint(struct checkPoints **checkPoint) {
    struct checkPoints *checkPt = *checkPoint;

    while (checkPt != NULL) {
        if (checkPt->next == NULL) {
            scanf("%c %d %d %d %d", checkPt->dropOut, checkPt->currentPoint, checkPt->competitor, checkPt->hour, checkPt->minute);
        }
        checkPt = checkPt->next;
    }
}

答案 2 :(得分:1)

试试这个

 void addCheckPoint(struct checkPoints **checkPoint) {
        struct checkPoints *checkPt = *checkPoint;

        while (checkPt->next != NULL) {
             checkPt=checkPt->next;
            if (checkPt == NULL) {
                scanf("%c %d %d %d %d", &checkPt->dropOut, &checkPt->currentPoint, &checkPt->competitor, &checkPt->hour, &checkPt->minute);
            }

        }
    }

答案 3 :(得分:0)

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

struct checkPoints
{
    char dropOut;
    int currentPoint;
    int competitor;
    int hour;
    int minute;

  struct checkPoints *next;
};

void addCheckPoint(struct checkPoints **checkPoint) {
    while (*checkPoint)
        checkPoint = &(*checkPoint)->next;

    /* FIXME: check malloc() return value */
    *checkPoint = malloc(sizeof (struct checkPoints));
    (*checkPoint)->next = 0;

    /* NOTE: the leading space in front of the %c */
    scanf(" %c %d %d %d %d",
          &(*checkPoint)->dropOut,
          &(*checkPoint)->currentPoint,
          &(*checkPoint)->competitor,
          &(*checkPoint)->hour,
          &(*checkPoint)->minute);
}

struct checkPoints *list = 0;

int
main ()
{
    addCheckPoint (&list);
    addCheckPoint (&list);
}