从键盘上输入5个数据建立一个单链表求大神帮助

实验内容:从键盘上输入5个数据建立一个单链表,并且输出该单链表。(部分代码已经给出,只需在输入线性表数据和输出线性表数据处添加代码即可) 实验目的:加深对c语言的使用。 /*creat a list*/ #include "stdlib.h" #include "stdio.h" //定义一个结点 struct list { }; typedef struct list node; typedef node *link; void main() {link ptr,head; int num,i; head=(link)malloc(sizeof(node)); ptr=head; printf("please input 5 numbers==>尀n"); //从键盘上输入5个数据建立一个单链表 for(i=0;i<=4;i++) { } //输出单链表的数据 ptr=head; while(ptr!=NULL) { } }
2026年09月24日 03:28
有1个网友回答
网友(1):

/*creat a list*/ #include "stdlib.h" #include "stdio.h" //定义一个结点 struct list { int data; struct list *next; }; typedef struct list node; typedef node *link; void main() {link ptr,head,s,pre; int num,i; head=(link)malloc(sizeof(node)); ptr=pre=head; printf("please input 5 numbers==>\n"); //从键盘上输入5个数据建立一个单链表 for(i=0;i<=4;i++) { scanf("%d",&num); ptr->data=num; s=(link)malloc(sizeof(node)); pre=ptr; ptr->next=s; ptr=s; } pre->next=NULL; //输出单链表的数据 ptr=head; while(ptr!=NULL) { printf("%4d",ptr->data); ptr=ptr->next; } return 0; }