2012-12-14 55 views
0

我遇到了一個問題,我想添加項到鏈表的末尾,但似乎我在這裏被無限循環吸入。無限循環在鏈表C

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); 
     } 
    } 
} 
+2

如何將'checkPt-> next'過改變嗎? – chill

+0

將checkpt移到下一個節點。 – Jeyaram

+0

http://stackoverflow.com/questions/13875395/linked-list-head-address-changes-c – anishsane

回答

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; 
    } 
} 
3

您從不更新循環中的checkPt的值。行

checkPt->next; 

更改爲

checkPt = checkPt->next; 

來解決這個問題。

請注意,該功能可能還存在其他問題。儘管它的名字,它實際上並沒有添加任何東西到列表中。它編輯尾部項目的內容。如果這不是故意的,則需要malloc一個新元素,然後將其添加到尾部。

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); 
      } 

     } 
    } 
+0

你也必須改變條件循環.. –

+0

哪些條件? –

+0

我認爲這樣會好的 –

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); 
}