我試圖插入一個節點到鏈表的末尾,並且所有的工作都像奇蹟般,但是,當它涉及到最後一個元素時,它會打印出null
。有問題必須在else
塊,我在想,當我尋找的最後一個項目可能指向NULL
而不是有next
作爲NULL
鏈接列表,一個元素會丟失
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define HOW_MANY 7
char *names[HOW_MANY]= {"Simon", "Suzie", "Alfred", "Chip", "John", "Tim",
"Harriet"};
int ages[HOW_MANY]= {22, 24, 106, 6, 18, 32, 24};
struct person {
int age;
char *name;
struct person *next;
};
struct person* insert_end(struct person *ptr, char *name, int age)
{
//The new location for the new person
struct person* newPer = malloc(sizeof(struct person));
if (newPer == NULL) {
printf("something went wrong allocating the memory\n");
exit(1);
}
newPer -> name = name;
newPer -> age = age;
//Make its next points previous element
if (ptr->next == NULL) {
newPer -> next = ptr;
return newPer;
}
else {
struct person *tmp = ptr;
while(tmp -> next != NULL){
tmp = tmp -> next;
}
printf("%s", tmp -> name);
tmp -> next = newPer;
//if(strcmp("Harriet",name)==0)
return ptr;
}
//return the new address so that it becomes the new HEAD of the linked list
return newPer;
}
int main(int argc, char **argv)
{
//This is the head of the list
struct person *HEAD = NULL;
HEAD = malloc(sizeof(struct person));
if (HEAD == NULL) {
printf("something went wrong allocating the memory");
exit(1);
}
int i;
//insert a new person and make HEAD points to it, so that HEADS
//will be pointing to the last element added to the linked list.
for (i = 0; i < HOW_MANY; i++){
HEAD = insert_end (HEAD, names[i], ages[i]);
}
struct person* tmp = HEAD;
//We can use the member name(pointer) as the condition, if we did then extra
//unwanted elements added to the linked list by accident won't be printed
while (tmp != NULL){
if (tmp -> next != NULL)
printf("The name is %s, the age is %d years\n", tmp->name, tmp->age);
//store the pointer in a tmp so than we can access the next pointer then
//free tmp
struct person* prevtmp = tmp;
tmp = tmp -> next;
free(prevtmp);
}
}
輸出是
The name is Simon, the age is 22 years
The name is (null), the age is 0 years
The name is Suzie, the age is 24 years
The name is Alfred, the age is 106 years
The name is Chip, the age is 6 years
The name is John, the age is 18 years
The name is Tim, the age is 32 years
這段代碼甚至應該在最後一位做什麼?只是列出清單? –
你的第一個分配元素('main'的頂部)永遠不會獲得'name'。 –
最後一點只是將所有內容都打印出來 – Zed