首页 > 解决方案 > 删除所有大于特定值的数字

问题描述

我正在尝试执行一种算法来删除队列中大于特定值的所有数字,这是我的代码。

void problem(Queue* c, int x) {
    if (isEmpty(c)) {
        printf("empty queue");       
    } else {
        Node* n1 = c->top; 
        Node* n2 = c->top->next;
        while (n2 != NULL) {
            if (n2->value > x) {
                Nodo* aux = n2;
                n1->next = aux->next;
                aux->next = NULL;
                free(aux);
            }
            n1 = n2;
            n2 = n2->next;
        }
    }
}

标签: calgorithmdata-structureslinked-listqueue

解决方案


if条件为真时,就会出现问题。在这种情况下,您不想在该if块之后继续使用n1 = n2;,因为n2现在是对已删除节点的引用。另一方面,您仍然需要移动n2以指向下一个节点,因此这应该在当前节点被释放之前if发生在块中。

这样做:

void problem(Queue* c, int x) {
    if (isEmpty(c)) {
        printf("empty queue");       
    } else {
        Node* n1 = c->top; 
        Node* n2 = c->top->next;
        while (n2 != NULL) {
            if (n2->value > x) {
                Node* aux = n2;
                n2 = n2->next; // <-- add this; n1 remains unchanged.
                n1->next = n2; // <-- now this can be shorter code
                free(aux);
            } else { // Make conditional
                n1 = n2;
                n2 = n2->next;
            }
        }
    }
}

aux->next = NULL;没有错,但也不需要,因为该节点已被释放。


推荐阅读