在牛客网运行一道很简单的代码题时报错“您的程序发生段错误,可能是数组越界,堆栈溢出(比如,递归调用层数太多)等情况引起”
题目要求:
我的代码如下:
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node {
int data;
struct node* next;
}* Lnode;
void InitLink(Lnode l) {
l = (Lnode)malloc(sizeof(struct node));
l->next = NULL;
}
void insert(Lnode l, int x, int y) {
Lnode newnode = (Lnode)malloc(sizeof(struct node));
newnode->data = y;
Lnode p = l;
while (p->next != NULL) {
if (p->next->data == x) {
break;
}
p = p->next;
}
newnode->next = p->next;
p->next = newnode;
}
void delete (Lnode l, int x) {
Lnode p=l,q;
while (p->next != NULL) {
if (p->next->data == x) {
q = p->next;
p->next = p->next->next;
free(q);
break;
}
else
p = p->next;
}
}
int main() {
int n = 0;
char s[20];
Lnode mylink;
InitLink(mylink);
scanf("%d", &n);
while (n--) {
scanf("%s", s);
if (!strcmp(s, "insert")) {
int x, y;
scanf("%d %d", &x, &y);
insert(mylink, x, y);
}
if (!strcmp(s, "delete")) {
int num;
scanf("%d", &num);
delete (mylink, num);
}
}
if(mylink->next==NULL)
printf("NULL");
else{
while(mylink->next!=NULL){
printf("%d ",mylink->next->data);
mylink=mylink->next;}
}
return 0;
}