2015-11-07 87 views
1

我想在末尾添加一个条目到链接列表,但无法处理指针。这里是我的链接列表:将条目附加到链接列表的末尾

struct list { 
    int val; 
    list *next; 
}; 

我宣布名单aList全球:

struct list *aList; 

并具有以下功能:值添加到列表:

void add(int var) { 
    struct list *temp = aList; 
    if (temp == NULL) { //if aList is empty 
     temp = malloc(sizeof(struct list)); 
     temp->val = var; //add it to first spot 
     temp->next = NULL; 
    } else { //if aList is not empty 
     while (temp->next != NULL) { //find the first empty spot 
      temp = temp->next; 
     } 
     temp = malloc(sizeof(struct list)); 
     temp->val = var; //add it to empty spot 
     temp->next = NULL; 
    } 
} 

我米真的失去了指针。我想添加到aList,所以我需要创建一个临时列表指向它并添加到(任何更改反映在aList)。如果不使用临时列表,我将失去列表的结构,并且它将包含1或0个元素,而不管我添加了多少个元素。

说我想要做如下:

for (int i = 0; i < 5; i++) { add(i); } 

我想aList1->2->3->4->5->NULL并能够访问它从1开始。

+0

将东西添加到链接列表的开头更容易。只需将新的“下一个”指针设置为列表头部,并将列表aList的头部设置为新的头部。 –

+0

@PaulTomblin即使这样,我需要添加第一个值,即使没有元素,'temp'也不是NULL。 – gator

+0

您的'add'方法会将'malloc'结果存储到一个局部变量'temp'中,所以'aList'永远不会更新。 'temp'不指向'aList',而是指向'aList'指向的内容。只改变你的'then'的一部分,如果只使用'aList'。 – Kenney

回答

2
while (temp->next != NULL) { //find the first empty spot 
     temp = temp->next; 
    } 
    temp = malloc(sizeof(struct list)); 

当您这样做时,您正在覆盖最后一个元素。

相反,您需要将其分配给新节点。

struct list *newnode = malloc(sizeof(struct list)); 
// Fill newnode 
temp->next = newnode; 
+0

或'temp-> next = malloc(sizeof(struct list));温度= TEMP->下;' –