头插法建立单链表

windows vc6.0++下通过
输入数字,-1结束;

#include<stdio.h>
typedef struct link//定义一个结构体,里面只有一个int数据 *next用来存放下一个节点的地址
{

int data;
struct link *next;

}LINK;

//////////////////////////////////////单链表的建立//////////////////////////////////////////////////
//////////////////////////////////////////头插法////////////////////////////////////////////////////
struct link *creat_link()
{
int a;
struct link *h,*new;
h=(LINK*)malloc(sizeof(LINK));//搞一个头节点
scanf("%d",&a);//输入一个int变量a
while(a!=-1)
{
new=(LINK*)malloc(sizeof(LINK));
new->data=a;//把变量a的数据输入new的data中,类似new.data=data
new->next=h->next;//把新的数据的下一个地址改成头节点里存放的地址,这样新数据就在整个链表头部了。
h->next=new;//把新的节点的地址给头节点的存放地址区,这样才能在表头插入下一个数据。
scanf("%d",&a);//在开始写数据
}

return h;



}

void main()
{


struct link *head;//先创立一个头节点
head=creat_link();

}

运行结果

猜你喜欢

转载自blog.csdn.net/weixin_42828324/article/details/81281838