C++链表初始化失败
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
typedef struct LNode{
int data;
struct LNode*next;
}LinkList;
typedef struct LNode LinkList;
void InitLinkList(LinkList *head)
{
(head)=(LinkList*)malloc(sizeof(LNode));
(head)->next=NULL;
(head)->data=0;
}
void Insert(LinkList *head,int data)
{
printf("开始建立节点:\n");
LNode*node=(LNode*)malloc(sizeof(LNode));
node->data=data;
node->next=NULL;
/*开始插入节点*/
printf("开始插入节点:\n");
LNode *p=head;
while(head->next!=NULL)
p=p->next;
p->next=node;
printf("插入节点完毕:");
}
int main()
{
LinkList *head=NULL;
InitLinkList(head);
for(int i=0;i<3;i++)
Insert(head,i);
}
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
typedef struct LNode{
int data;
struct LNode*next;
}LinkList;
typedef struct LNode LinkList;
void InitLinkList(LinkList **head)//这里改为LinkList**。。否则改变的只是head的副本。。不是head本身。。
{
(*head)=(LinkList*)malloc(sizeof(LNode));
(*head)->next=NULL;
(*head)->data=0;
}
void Insert(LinkList *head,int data)
{
printf("开始建立节点:\n");
LNode*node=(LNode*)malloc(sizeof(LNode));
node->data=data;
node->next=NULL;
/*开始插入节点*/
printf("开始插入节点:\n");
LNode *p=head;
while(p->next!=NULL)//这里是p->next不是head->next。。
p=p->next;
p->next=node;
printf("插入节点完毕:");
}
int main()
{
LinkList *head=NULL;
InitLinkList(&head);
for(int i=0;i<3;i++)
Insert(head,i);
}