关于#链表无效内存引用#的问题,如何解决?

求帮忙改程序
题目如下
对给定的单链表 L ,设计一个算法,删除 L 中值为 x 的结点的直接前驱结点。
测试输入 期待的输出 时间限制 内存限制 额外进程
测试用例 1
11 22 33 44 55 66 77↵
44↵

11 22 44 55 66 77↵
1秒 64M 0
测试用例 2
23 45 11 45 67 88 4 33 78↵
88↵

23 45 11 45 88 4 33 78↵
1秒 64M 0
测试用例 3
12 23 34 45 56 67 78 89↵
12↵

该结点没有前驱结点↵
1秒 64M 0
我的程序

我的问题
RE: 无效内存引用

#include
#include
struct Lnode
{
    int data;
    Lnode *next;
}Lnode;
int main(){
int a[10],cou1,cou2;
for(int i=0,cou1=0;a[i]!='\n';i++){
scanf("%d",&a[i]);
cou1++;
}
int m;
scanf("%d",&m);
for(int i=0;a[i]!='\n';i++){
printf("%d\n",a[i]);
}
struct Lnode *head;
struct Lnode *p;
p=(struct Lnode*)malloc(sizeof(struct Lnode));
p->next=NULL;
head=p;
if(p->data==a[0]) printf("该结点没有前驱结点\n");
else{
for(int n=1,cou2=0;p->data!=m;n++)
{
cou2++;
if(p->next=NULL) return 1;
else p++;
}
struct Lnode *q;
q=(struct Lnode*)malloc(sizeof(struct Lnode));
q->next=NULL;
head=q;
for(int j=0;qprintf("%d",a[j]);
}
for(int k=cou2+1;k<=cou1;k++)
{
printf("%d",a[k]);
}
printf("\n");
return 0;
}
}

基于Monster 组和GPT的调写:

#include <stdio.h>
#include <stdlib.h>

struct Lnode {
    int data;
    struct Lnode* next; // 修改1:将结构体成员的类型从 Lnode 改为 struct Lnode
};

int main() {
    int a[10], cou1 = 0; // 修改2:将 cou1 的初始化值改为 0
    char c;
    // 修改3:读取数组时,使用 scanf 读取数字并忽略空格和换行符
    while (scanf("%d%c", &a[cou1], &c) == 2 && c != '\n') {
        cou1++;
    }
    int m;
    scanf("%d", &m);
    // 修改4:输出链表时,使用循环遍历链表而不是数组
    struct Lnode* head = NULL;
    struct Lnode* p = NULL;
    struct Lnode* q = NULL;
    for (int i = 0; i < cou1; i++) {
        struct Lnode* node = (struct Lnode*)malloc(sizeof(struct Lnode));
        node->data = a[i];
        node->next = NULL;
        if (head == NULL) {
            head = node;
        } else {
            p->next = node;
        }
        p = node;
        // 如果当前节点的值是 m,那么记录当前节点的前一个节点为 q
        if (node->data == m) {
            q = p;
        }
    }
    // 如果 q 是 NULL,说明 m 在链表头部,没有前驱结点
    if (q == NULL) {
        printf("该结点没有前驱结点\n");
        return 0;
    }
    // 如果 q 是 head,说明 m 的前驱结点是 NULL
    if (q == head) {
        printf("该结点没有前驱结点\n");
        return 0;
    }
    // 否则,删除 q 的前一个节点
    struct Lnode* pre = head;
    while (pre->next != q) {
        pre = pre->next;
    }
    pre->next = q->next;
    // 输出删除前驱结点后的链表
    struct Lnode* curr = head;
    while (curr != NULL) {
        printf("%d ", curr->data);
        curr = curr->next;
    }
    printf("\n");
    return 0;
}


主要的修改包括:

将结构体成员的类型从 Lnode 改为 struct Lnode,因为在 C 语言中结构体的类型需要加上 struct 关键字。

将 cou1 的初始化值改为 0,因为没有进行初始化的变量的值是不确定的。

读取数组时,使用 scanf 读取数字并忽略空格和换行符。

输出链表时,使用循环遍历链表而不是数组。

此外,程序还进行了一些其他的修改,如将链表的头节点 head 初始化为 NULL,修改了链表的构建方式,以及使用了指针来记录要删除的节点的前一个节点等。

%d输入整型,怎么用a[i]!='\n'作为输入结束条件呢???换行符是不会输入到整型数组的啊