1

引数に渡された値を持つすべてのノードを削除するコードを次に示します。

typedef struct nodetype
{
    int data;
    struct nodetype * next;
} node;

typedef node * list;


void Linklist::deleteNode(list * head, int value)
{

    list current = *head;
    list previous = *head;
    while(current != NULL)
    {
        if(current->data != value)
        {
              previous = current;
              current = current->next;
        }

        else if (current->data == value)
        {
            previous->next = current->next;
            delete current;
            current = previous->next;

        }
    }
} 

しかし、ここでリンクリストのすべての要素が2である場合、リンクリストのすべての要素を削除し、最終的にヘッドもNULLになる必要があるため、このヘッドを渡してリスト内のノードの数をカウントすると、リストは空で、他の同様の操作です。

私の現在の実装によれば、上記のケースでは頭は NULL になりません。

関数の引数に同じ値が渡されたすべてのノードが linklist にある場合、 head が NULL になるように変更を提案してください。

4

1 に答える 1

2

次のようにコードを変更し、その作業ファイルを現在

void Linklist::deleteNode(list *head, int value)
{

    list * current = head;
    list * previous = head;
    bool flag = false;
    while(*current != NULL)
    {
        if((*current)->data != value)
        {
            *previous = *current;
            *current = (*current)->next;
        }

        else if ((*current)->data == value)
        {
            flag = true;
            (*previous)->next = (*current)->next;
            delete *current;
            *current = (*previous)->next;

        }
    }
    if(!flag)
        cout<<"Element not found in the linklist\n";
    cout<<"Count is "<<Linklist::count(*head)<<endl;
}
于 2012-04-17T20:14:50.457 に答える