在 C 中的节点或元素中插入新数据时出现链表错误


#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int info;
struct node* next;
}Node;
typedef Node* list;
void printlist(list n)
{
while(n!=NULL)
{
printf("%d ",n->info);
n=n->next;
}
}
int main()
{
printf("Hello world!n");
list head,temp;
char ch;
head=NULL;
printf("Want to add data:n");
scanf("%c",&ch);
while(ch=='y'||ch=='Y')
{
temp=(list)malloc(sizeof(Node));
scanf("%d",&temp->info);
temp->next=head;
head=temp->next;
printf("Want to add more data:n");
scanf("%c",&ch);
}
printlist(head);
return 0;
}

这是我的代码。 我的问题在这里,我不能和我列表中的数据,但节点已添加...... 我认为我的"scanf"功能有问题.... 请帮助我解决此问题并将更正后的代码发送给我

thank u...hope I can get a reply soon

尝试更改 head=temp->旁边 head=temp。你又把头分配给自己了。

除了上述答案之外,如果您希望保持元素添加到链表的顺序(头部始终保持固定,如果最初为 NULL,则仅更改为指向第一个元素(,以下调整可以解决这个问题。任何新元素总是被添加到链表的末尾,头部固定在第一个元素上。

#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int info;
struct node* next;
}Node;
typedef Node* list;
void printlist(list n)
{
while(n!=NULL)
{
printf("%d ",n->info);
n=n->next;
}
}
int main(){
printf("Hello world!n");
list head,temp;
char ch;
head=NULL;
printf("Want to add data:n");
scanf("%c",&ch);
while(ch=='y'||ch=='Y'){
temp=(list)malloc(sizeof(Node));
scanf("%d",&temp->info);
temp->next=NULL;
if(head == NULL){
head = temp;
}
else{
list temp2 = head;
while(temp2->next != NULL){
temp2 = temp2->next;
}
temp2->next = temp;
}
printf("Want to add more data:n");
scanf(" %c",&ch);
}
printlist(head);
return 0;
}

按如下方式更改代码。 scanf("%c",&ch(; to scanf(" %c",&ch(; 和头=临时->下一个; 到头=温度;有关 Scanf,请参见以下链接 请参阅链接 scanf(( 函数不起作用?

#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int info;
struct node* next;
}Node;
typedef Node* list;
void printlist(list n)
{
while(n!=NULL)
{
printf("%d ",n->info);
n=n->next;
}
}
int main()
{
printf("Hello world!n");
list head,temp;
char ch;
head=NULL;
printf("Want to add data:n");
scanf(" %c",&ch);
while(ch=='y'||ch=='Y')
{
temp=(list)malloc(sizeof(Node));
scanf("%d",&temp->info);
temp->next=head;
head = temp;
printf("Want to add more data:n");
scanf(" %c",&ch);
}
printlist(head);
return 0;
}

最新更新