通过while 调用创建
#include <stdio.h>
#include <stdlib.h>
struct Test
{
int data;
struct Test *next;
};
struct Test *createLinks(struct Test *head)
{
struct Test *new;
new = (struct Test*)malloc( sizeof(struct Test) );
printf("input data to create links:\n");
scanf("%d",&(new->data));
if(head == NULL){
head = new;
return head;
}else{
new->next = head;
head = new;
return head;
}
}
void printLinks(struct Test *head)
{
struct Test *p = head;
while(p != NULL){
printf("data = %d\n",p->data);
p = p->next;
}
}
int main()
{
int i = 3;
struct Test *head;
while(i--){ //调用3次 创建3次
head = createLinks(head);
}
printLinks(head);
return 0;
判断输入为0 停止创建
#include <stdio.h>
#include <stdlib.h>
struct Test
{
int data;
struct Test *next;
};
struct Test *createLinkFor(struct Test *head)
{
struct Test *new = NULL;
while(1){
new = (struct Test*)malloc( sizeof(struct Test) );
printf("input data to create links:\n");
scanf("%d",&new->data);
if(new->data == 0){ //输入为0时 停止创建链表
free(new);//释放空间
printf("exit\n");
return head;
}
if(head == NULL){
head = new;
}else{
new->next = head;
head = new;
}
}
}
void printLink(struct Test *head)
{
struct Test *p;
p = head;
while(p != NULL){
printf("data = %d\n",p->data);
p = p->next;
}
}
int main()
{
struct Test *head = NULL;
head = createLinkFor(head);
printLink(head);
return 0;
}
头插法的改进:
#include <stdio.h>
#include <stdlib.h>
struct Test
{
int data;
struct Test *next;
};
struct Test *insertLink(struct Test *head,struct Test *new)
{
if(head == NULL){
head = new;
}else{
new->next = head;
head = new;
}
}
struct Test *createLink(struct Test *head)
{
struct Test *new;
while(1){
new = (struct Test*)malloc( sizeof(struct Test) );
printf("input data to create links:\n");
scanf("%d",&(new->data));
if(new->data == 0){
printf("quit\n");
return head;
}
head = insertLink(head,new);
}
}
void printLinks(struct Test *head)
{
struct Test *p = head;
while(p != NULL){
printf("data = %d\n",p->data);
p = p->next;
}
}
int main()
{
struct Test *head;
head = createLink(head);
printLinks(head);
return 0;
}