我编写这段代码是为了让用户在列表中输入他们想要的节点数,以及每个节点的元素。只有当我尝试打印列表的值时,我的错误才会发生。好像我只打印列表的第一个值。或者我没有成功地将数据分配给列表。
注意“list.h”只包括stdio 和stdlib 库,以及结构定义。它只保存数据和指向同一结构的指针。
#include "list.h"
struct node *head = NULL;
void print_data(){
struct node* temp;
temp = head;
printf("\n\n");
while(temp != NULL){
printf("%d ", temp->data);
temp = temp->next;
}
}
void insert(data){
struct node *temp = malloc(sizeof(struct node));
struct node *p;
temp->data = data;
temp->next = NULL;
if( head == NULL ){
head = temp;
}else{
p = head;
while( p->next != NULL){
p = p->next;
p->next = temp;
}
}
}
int main(){
int i, amount, element;
printf("\nEnter Amound of Nodes: \n");
scanf(" %d", &amount);
for( i = 0; i < amount; ++i){
printf("\nEnter Node #%d amount ", i + 1);
scanf(" %d", &element);
insert(element);
}
print_data();
}
最佳答案
您的插入有误。假设你想在链表的最后插入节点。但是您的代码在列表的开头插入节点而没有正确处理列表的其余部分。因此,您列表的其余部分将会丢失。
while( p->next != NULL){
p = p->next;
p->next = temp;
}
应该是
while( p->next != NULL){
p = p->next;
}
p->next = temp;
关于c - 打印链表数据时只打印第一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51815289/