单链表插入数据
#include
定义/
typedef struct link//定义一个结构体,里面只有一个int数据 *next用来存放下一个节点的地址
{
int data;
struct link *next;
}LINK;
//单链表的插入
/*
功能:在值为x的节点之后插入值为y的节点,并返回1,不存在x则返回0
*/
int insert_link(struct link *head,int x,int y)
{
struct link *new,*q;
q=head->next;
while((q!=0)&&(q->data!=x))
q=q->next;
if(q==0)
{return 0;}
new=(LINK *)malloc(sizeof(LINK));
new->data=y;
new->next=q->next;
q->next=new;
return 1;
}
//访问单链表
void print_link(struct link *head)
{
struct link *q;
q=head->next;
if(!q)
printf("linklist is null\n");
else
{
do
{
printf("%5d",q->data);
q=q->next;
}while(q);
}
}
//单链表的建立//
//头插法
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();
insert_link(head,3,99);
print_link(head);
}