【发布时间】:2019-04-20 15:57:16
【问题描述】:
您好,我是学习链接列表的新手,我创建了这个示例程序,但它没有填充所有列表,只有最后两个被填充(或者这些覆盖了第一个链接元素)
有人可以帮我解决问题的原因吗?
#include<stdio.h>
#include<stdlib.h>
struct node {
int data;
struct node *link;
};
void appendNode(int data, struct node **ptr) {
struct node *newnode = (struct node*)malloc(sizeof(struct node));
newnode->data = data;
newnode->link = NULL;
if(*ptr == NULL) {
*ptr = newnode;
} else {
while((*ptr)->link != NULL ) {
*ptr = (*ptr)->link;
}
(*ptr)->link = newnode;
}
}
void printList(struct node *node)
{
while (node != NULL)
{
printf(" %d ", node->data);
node = node->link;
}
}
int main() {
struct node *head = NULL ;
appendNode(23,&head);
appendNode(45,&head);
appendNode(32,&head);
appendNode(11,&head);
appendNode(98,&head);
printList(head);
}
红外打印
11 98
是什么导致了这里的问题?
【问题讨论】:
-
只跟踪最后一个节点而不是在每次要插入时使用
while循环扫描整个列表不是更容易吗?
标签: c data-structures linked-list insertion