这个链表函数有什么问题?

What's wrong with this linked list function?

本文关键字:什么 问题 函数 链表      更新时间:2023-10-16

上下文是L链表中的一个。我假设L在开头不是0,并且每个链表都以一个节点结尾,该节点的下一个字段为NULL。

void g(node*, int, char);
void g(node* L, int k, char y) {
    node* current = L;
    if (current->info == y) k--;
    while (current->next) {
        if (current->next->info == y) {
            if (k > 0) k--;
            else {
                node* very_next = current->next->next;
                delete current->next;
                current->next = very_next;
            }
        }
        current = current->next;
    }
}

我一直收到一个级别为while(current->next)的BAD_ACCESS警告。怎么了?我正在访问一个正确的节点,因为测试(!current->next)失败了。那怎么了?

我正在测试的链接列表是

node* n = new node('a',new node('b', new node('a', new node('c', new node('a', 0)))));

具有此结构:

struct node {
    char info;
    node* next;
    node(char a = 0, nodo* b = 0) {
        info = a;
        next = b;
    }
};

如果是current->next->next == very_next = NULL,current是否也会被分配NULL,从而使以后对current的访问(通过current->next)无效(current = current->next = very_next)?

您在循环中认为current->next->next指向下一个元素的假设可能是错误的,您应该首先检查这是否为真。