链表头插法编程实现

头插法思想就是建立一个头结点,自己指向自己,然后新来一个结点,

就让这个新结点指向头结点所指向的结点,然后让头结点指向新来的结点。

这样把新结点永远插到头结点之后就是头插法了。

C语言编程实现

#include<stdio.h>
#include<malloc.h>
struct list {  
    int a;  
    struct list * next;
} ;  
struct list * head;
struct list * p=NULL; 
int main(){
	printf("%s\n","请输入链表的长度");
	int length=0,i,data;
	scanf("%d",&length);
	printf("%s\n","请依次输入链表中的数据");
    head = (struct list *)malloc(sizeof(struct  list));
	head->next=NULL;
	for(i=0;i<length;i++){
		p = (struct list *)malloc(sizeof(struct  list));
		scanf("%d",&p->a);
	    p->next=head->next; 
	    head->next=p; 
	}
	while(p!=NULL){
		 printf("%d  ",p->a);
	     p=p->next;
	}
}