关于单链表的插入
使用下面的插入函数向单链表插入数据时报错,报错提示为Thread 1: EXC_BAD_ACCESS (code=2, address=0x10000000a)报错的地方是insert函数的 p->next = s;部分,环境为xcode,使用c语言。enum Status List_Insert(SqListPtr L,int pos,ElemType elem)
{
enum Status status = fail;
Ptr p,s;
p = (Ptr)malloc(sizeof(Node));
status =List_Retrieve(L,pos-1,&p);
if (status==success) {
s = (Ptr)malloc(sizeof(Node));
s->elem = elem;
s->next = p->next;
p->next = s;
status = success;
}else status = range_error;
return status;
}
链表的头文件定义为
typedef int ElemType;
typedef enum Status
{
success = 1, fail = 0, fatal = -1, range_error = -2
}Status;
typedef struct Node
{
ElemType elem;
struct Node *next;
}Node, *Ptr,**SqListPtr;
其余相关函数为
enum Status List_Init(SqListPtr L)
{
Status s = fail;
Ptr p;
if (*L==NULL)
{
p = (Ptr)malloc(sizeof(Node));
if (p == NULL) return s;
*L = p;
(*L)->next = NULL;
s = success;
}
return s;
}
enum Status List_Create(SqListPtr L,ElemType Data[],int Len)
{
enum Status s;
Ptr p;
s = List_Init(L);
if (s == success) {
for (int i = Len-1;i>=0 ;--i ) {
p = (Ptr)malloc(sizeof(Node));
if (p) {
p->elem = Data[i];
p->next = (*L)->next;
(*L)->next = p;
}
else{
s = fail;
break;
}
}
}
return s;
}
void List_Print(SqListPtr L)
{
Ptr p = *L;
while(p->next) {
p = p->next;
printf("%d\n",p->elem);
}
}
enum Status List_Retrieve(SqListPtr L,int pos,ElemType *elem)
{
enum Status s = range_error;
Ptr p = (*L)->next;
int i = 1;
while ( p && i<pos) {
i++;
p=p->next;
}
if (p&&i==pos) {
*elem = p->elem;
s = success;
}
return s;
}
int main() {
SqListPtr L = (SqListPtr)malloc(sizeof(Node));
int len = 5;
int Data[] = {1,2,3,4};
List_Create(L, Data, len);
int delepos = 3;
List_Insert(L,delepos,23);
return 0;
}