仅删除链表中最后一个节点旁边的不存在节点终止程序

deleting only non-existing node which is right next to last node in linked list terminates the program

当我删除链表中存在的任何节点时,我的代码可以完美运行。 假设我的链表有 10 个节点,如果我想删除第 12、13、14...节点,我的程序会给我预期的消息。

但是如果我想删除 11th 节点(与最后一个节点相邻),我的程序将以退出代码终止 -1073741819 (0xC0000005)

int delete()
{
    int position, count = 1;
    printf( "\nwrite your position" );
    scanf( "%d", &position );

    struct node *p, *q;
    p = head;
    if ( position == 0 ) {
        p = p->next;
        head = p;
        return 0;
    }
    while ( p != NULL && count != position ) {
        count++;
        p = p->next;
    }
    count = 0;
    if ( p == NULL ) {
        printf( "link list is empty or link not found\n" );
        return 0;
    }
    else {
        q = p->next;
        p->next = q->next;
    }
}

pNULL 时,此语句无效

p->next = q->next;

所以,解决方案是将 p->next == NULL 语句添加到 if 条件 像这样:-

if ( p == NULL || p->next == NULL ) {
    printf( "link list is empty or link not found\n" );
    return 0;
}

现在正确的代码是

int delete()
{
    int position, count = 1;
    printf( "\nwrite your position" );
    scanf( "%d", &position );

    struct node *p, *q;
    p = head;
    if ( position == 0 ) {
        p = p->next;
        head = p;
        return 0;
    }
    while ( p != NULL && count != position ) {
        count++;
        p = p->next;
    }
    count = 0;
    if ( p == NULL || p->next == NULL ) {
        printf( "link list is empty or link not found\n" );
        return 0;
    }
    else {
        q = p->next;
        p->next = q->next;
    }
}

when i delete qny node present in a linked list my code works perfect

不,不是。删除索引 0 处的节点看起来不错,但对于任何其他正索引 n,它会尝试删除索引 n+1 处的节点通过推进指针 p 指向节点 n 然后操纵 p->next.

but if i want to delete 11th node(which is adjacent to last node) ,my program terminates with exit code -1073741819 (0xC0000005)

我不相信,但我相信当您尝试删除 last 节点(而不是最后一个节点)时程序会失败。在这种情况下,p 被提前指向最后一个节点,其 next 指针为空。因此这段代码:

    q=p->next;
    p->next=q->next;

q 设置为空指针,然后尝试取消引用该指针。