头插法:新节点进来称为链表头,不断插入,头一直都是最新的节点。
#include <stdio.h>
#include <stdlib.h>
struct Test
{
int data;
struct Test *next;
};
void printLink(struct Test *head)
{
while(1){
if(head != NULL){
printf("%d ",head->data);
head = head->next;
}else{
printf("\n");
break;
}
}
}
struct Test* creatFromHead(struct Test *head)
{
struct Test *new;
while(1){
new = (struct Test *)malloc(sizeof(struct Test));
printf("input your new node data:\n");
scanf("%d",&(new->data));
if(new->data == 0){
printf("0 out\n");
return head;
}
if(head = NULL){
head = new;
}else{
new->next = head;
head = new;
}
}
return head;
}
int main(){
int i;
struct Test *head = NULL;
head = creatFromHead(head);
printLink(head);
return 0;
}