70,011
社区成员




#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int data;
struct node * next;
} Lnode;
//初始化链表
Lnode* init_create(int data)
{
Lnode *head,*p;//p用来接受系统为链表分配的内存,p1->next用来连接下一个节点地址
//当创建第一个节点的时候 为该节点分配内存
p=(Lnode*)malloc(sizeof(Lnode));
head=(Lnode*)malloc(sizeof(Lnode)); //建立头结点
//为节点的data取赋值 此时的p1要指向下一个节点 如果没有则为NULL
if(p!=0 && head!=0)
{
head->next = p;
p->data=data;//向data区添加数据,并设置下一个节点为NULL,此时已经到达了为节点,到了链表的尾部;
p->next=NULL;
}
else
{
printf("节点内存申请失败");
}
return head;
}
void Insert_Lnode(Lnode* head,int data)
{
//为插入的数据开辟内存
Lnode *p=(Lnode*)malloc(sizeof(Lnode));
//判断p是否为空
if(p)
{
p->data=data;
p->next=head->next;
head->next=p;
}
else
{
printf("内存申请失败");
}
}
void Printf_Lnode(Lnode* head)
{
Lnode *p;
p=head->next;
while(p!=NULL)
{
printf("%d ",p->data);
p=p->next;
}
}
int main(void)
{
Lnode * head = init_create(6);
Insert_Lnode(head,4);
Insert_Lnode(head,8);
Insert_Lnode(head,9);
Printf_Lnode(head);
return EXIT_SUCCESS;
}
程序可以正常输出。