链表:引发了访问权限错误,l->head是nullptr
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
typedef struct Node {
int val;
struct Node* next;
}Node;
typedef struct List {
Node* head;
int len;
}List;
Node* initNode(int val)
{
Node* n = (Node*)malloc(sizeof(Node));
n->val = val;
n->next = NULL;
return n;
}
void freeNode(Node* n)
{
if (n)
{
free(n);
}
}
List* initList()
{
List* l = (List*)malloc(sizeof(List));
l->head = NULL;
l->len = 0;
return l;
}
void freeList(List* l)
{
if (!l) {}
else
{
Node* p = l->head;
Node* k = NULL;
while (p)
{
k = p;
p = p->next;
freeNode(k);
}
free(l);
}
}
//插入节点到链表//
int insertNode(List* l, int idx, Node* n)
{
if (!l)
{
return 0;
}
if (idx<0 || idx>l->len)
{
return 0;
}
Node* p = (Node*)&(l->head);
while (idx--)
{
p = p->next;
}
n->next = p->next;
p->next = n;
l->len++;
return 1;
}
//插入数值到链表//
int insertVal(List* l, int idx, int val)
{
//生成一个新节点//
Node* n = initNode(val);
insertNode(l, idx, n);
if (!insertNode(l, idx, n))
{
freeNode(n);
return 0;
}
return 1;
}
//删除节点//
int erase(List* l, int idx)
{
if (!l)
{
return 0;
}
if (idx < 0 || idx >= l->len)
{
return 0;
}
//找到插入节点的前一个位置//
Node* p = (Node*) & (l->head);
while (idx--)
{
p = p->next;
}
Node* k = p->next;
p->next = p->next->next;
freeNode(k);
l->len--;
return 1;
}
int main()
{
void showList(List* l);
srand(time(0));
int cnt = 20;
List* l = initList();
while (cnt--)
{
int val = rand() % 100;
int opt = rand() % 4;
int idx = rand() % (l->len + 3) - 1;
switch (opt)
{
case 0:
case 1:
case 2:
printf("insert %d at %d,res=%s\n", val, idx, insertVal(l, idx, val) ? "SUC" : "ERR");
break;
case 3:
printf("erase at %d,res=%s\n", idx, erase(l, idx) ? "SUC" : "ERR");
break;
}
showList(l);
}
freeList(l);
return 0;
}
void showList(List* l)
{
if (!l) {}
else
{
Node* p = l->head->next;
printf("List:[");
while (p)
{
printf("%d->", p->val);
p = p->next;
}
printf("NULL]\n");
}
}
引发了未经处理的异常:读取访问权限冲突。
l->head 是 nullptr。
怎么修改才能使上面的程序运行,以及原因