-5
void deleteElement(LinkedListElement<char> *&pending)
{
    if (pending->Next) {
        char value = pending->Next->Data;
        pending->Data = value;
        LinkedListElement<char> *temp = pending->Next;
        pending->Next = pending->Next->Next;
        delete temp;
    }else{
        delete pending;
        pending = NULL;
    }
}

LinkedListElement<char> *l1 = new LinkedListElement<char>('a');
LinkedListElement<char> *l2 = new LinkedListElement<char>('b');
LinkedListElement<char> *l3 = new LinkedListElement<char>('a');
LinkedListElement<char> *l4 = new LinkedListElement<char>('c');
l1->setNext(l2); l2->setNext(l3); l3->setNext(l4);

printLinkedList(l1);
deleteElement(l4);
printLinkedList(l1);

我想问的 C++ 中简单棘手的删除节点在 else 语句中,如果链表是 end ,那么我可以删除 end 本身。

但是两个打印功能,总是打印abac,第二种方式是abac。因为我只是通过引用传递参数,(&),我想如果我想删除 l4 我不需要更改 l3->Next,因为我可以将 l4 更改为 NULL,而 l3->Next 将是 NULL。

我尝试使用

delete pending; pending=NULL;

为什么它不起作用,两个打印功能总是打印abac

4

1 回答 1

0

You delete l4, but you never change l3, and it points to l4s memory (now deleted) which still contains the data ('c')

You need to

l3->setNext(NULL);

to remove the element from the list (and you must still delete it of course)

To use the deleteElement function, you would need to change it to iterate through the list (Pseudo code):

void deleteElement( Element head , Element toBeDeleted)
{
    //are we deleting head (the first element of the list?) 
    //yes then head should be nulled, and delete as normal

    current = head ; ancestor = head;

    //scan through list (current becomes current->next until no more)
    //until we find toBeDeleted
    //maintain ancestor as we go 

    //if found set ancestor->next to current->next
    //delete toBeDeleted
}
于 2012-12-06T21:46:06.710 回答