单链表问题 请问我的代码错哪了 报内存读取错误

来源:百度知道 编辑:UC知道 时间:2024/06/25 03:41:56
#include "stdlib.h"
#include "malloc.h"
typedef char elemType;

typedef struct SNode
{
elemType data;
struct SNode *next;
}*LNode,Node;

void Init(Node *p)
{
p = (Node*)malloc(sizeof(Node));
p->data = "@";
if(!p)
{
printf("error!");
return;
}
p->next = NULL;
}

void insertfirst(Node *l,elemType x)
{
struct SNode *p;
struct SNode *newp = (Node*)malloc(sizeof(Node));
p = l;
newp->data = x;
newp->next = p->next;
p->next = newp;
}

void travel(Node *p)
{
p = p->next;
while(p != NULL)
{
printf("the data is : [%c]\n",p->data);
p=p->next;
}
}

void main()
{
int i = 0;
char a[]={'a','b','c','d'};
Node list;
Init(&list);

程序改成如下:

#include <stdio.h>
#include <malloc.h>
typedef char elemType;

typedef struct SNode
{
elemType data;
struct SNode *next;
}*LNode,Node;

void Init(LNode *p)
{
(*p)=(LNode)malloc(sizeof(Node));
if(!(*p))
{
printf("error!");
return;
}
(*p)->data = '@';
(*p)->next =NULL;
}

void insertfirst(Node *l,elemType x)
{
struct SNode *p;
struct SNode *newp = (Node*)malloc(sizeof(Node));
p = l;
newp->data = x;
newp->next = p->next;
p->next = newp;
}

void travel(Node *p)
{
p = p->next;
while(p != NULL)
{
printf("the data is : [%c]\n",p->data);
p=p->next;
}
}

void main()
{
int i = 0;
char a[4]={'a','b','c','d'};
LNode l