删除链接列表中的项目-程序不起作用

时间:2018-08-30 14:38:05

标签: c

我的程序上具有此功能,可以删除链表上的特定值,例如:

  

要删除的值:8

     

链接列表:2-> 9-> 8-> 3-> 5-> X

     

删除值后的列表:2-> 9-> 3-> 5-> X

问题是,它无法按预期工作。下面是我函数的代码:

void removeValue(DLList L, int value){
assert (L != NULL);
DLListNodeP curr = L->curr;
while (curr != NULL){
    if (curr->value == value){
        if (L->first == L->last){   // If there is only one item in the list
            L->curr = NULL;
            L->first = NULL;
            L->last = NULL;
            L->nitems = 0;
        }

        else if (L->curr->next == NULL){    // If current item is the last item on the list
            L->curr->prev->next = NULL;
            L->last = L->curr->prev;
            free (L->curr);
            L->last->next = NULL;
            L->curr = L->last;
            L->nitems--;
        }

        else if (L->curr->prev == NULL){ // If current item is the first item on the list
            L->curr = L->curr->next;
            free (L->curr->prev);
            L->curr->prev = NULL;
            L->first = L->curr;
            L->nitems--;
        }

        else {
            DLListNodeP next = L->curr->next;
            L->curr = NULL;
            L->curr = next;
            L->curr->prev->next = L->curr->next;
            L->curr->next->prev = L->curr->prev;
            L->nitems--;
        }

        L->curr = L->curr->next;
    }
    else {
        L->curr = L->curr->next;
    }
}

return; }

我曾经尝试一次修改代码,但仍然无法正常工作。我确实尝试了一切。有什么我可以做的才能使此代码起作用?谢谢

2 个答案:

答案 0 :(得分:0)

DLListNodeP prev = L->curr, next = L->curr->next; // Check if curr exists
if (prev->value == value) {
   L->curr = next;
   return;
}

while (next != NULL){
   if (next->value == value) {
      prev->next = next->next;
      break;
   }
   prev = next;
   next = next->next;
}

答案 1 :(得分:0)

您的代码似乎比需要的复杂。

我不确定L->curr是做什么用的,因为您已经有L->firstL->lastL->nitems

这是应该起作用的重构版本。请注意,我没有对其进行编译或测试,但它应该为您提供一个更好的起点:

void
removeValue(DLList L, int value)
{
    DLListNodeP prev;
    DLListNodeP next;
    DLListNodeP curr;

    assert(L != NULL);

#if 0
    curr = L->curr;
#else
    curr = L->first;
#endif

    if (curr != NULL)
        prev = curr->prev;
    else
        prev = NULL;

    // remove all matching nodes
    for (;  curr != NULL;  curr = next) {
        next = curr->next;

        // skip to next item if _not_ a  match
        if (curr->value != value) {
            prev = curr;
            continue;
        }

        // adjust forward link of previous node
        if (prev != NULL)
            prev->next = next;

        // adjust backward link of next node
        if (next != NULL)
            next->prev = prev;

        // adjust head of list if removing first item
        if (L->first == curr)
            L->first = next;

        // adjust tail of list if removing last item
        if (L->last == curr)
            L->last = prev;

        L->nitems--;
        free(curr);
    }
}