【问题标题】:deleting only non-existing node which is right next to last node in linked list terminates the program仅删除链表中最后一个节点旁边的不存在节点会终止程序
【发布时间】:2019-12-15 13:36:07
【问题描述】:

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

但如果我想删除 第 11 个 节点(与最后一个节点相邻),我的程序将以退出代码 -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;
    }
}

【问题讨论】:

  • 拿一张纸和一支铅笔,考虑一下列表只包含一个节点(头)并且位置设置为1的情况。
  • ^^^^ ... 或者列表为空(head == NULL),位置为0

标签: c linked-list singly-linked-list


【解决方案1】:

当我删除链表中存在的 qny 节点时,我的代码完美运行

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

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

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

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

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

【讨论】:

    【解决方案2】:

    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;
        }
    }
    

    【讨论】:

    • head 在开始时为空(即条目为空列表)时,如何解决?例如:假设head 为null,position 为0。会发生什么?
    猜你喜欢
    • 1970-01-01
    • 2016-06-11
    • 2013-03-25
    • 1970-01-01
    • 2014-05-22
    • 1970-01-01
    • 2019-06-08
    相关资源
    最近更新 更多