我正在尝试将一个节点插入链表的末尾,一切正常,但是,当涉及到最后一个元素时,它会打印 null
。 else
block 中一定有问题,我在想当我查找最后一项时它可能指向 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
最佳答案
只需将 if (tmp -> next != NULL)
更改为 if (tmp != NULL)
。您忘记了列表中的最后一个节点不会有“下一个”节点。
关于c - 链表,一个元素丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46838056/