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语句中,如果链表是结束的,那么我可以删除结尾本身。
但是两个打印功能,将始终打印abac,第二种方式abac。 因为我只是通过参考传递参数,(&amp;),我想如果我想删除l4 我不需要更改l3-&gt;接下来,因为我可以将l4更改为NULL,并且l3-&gt; Next将为NULL。
我尝试使用
delete pending; pending=NULL;
为什么它不起作用,两个打印功能总是打印abac
答案 0 :(得分:0)
你delete l4
,但你永远不会改变l3
,它指向l4
的内存(现已删除)仍包含数据('c')
你需要
l3->setNext(NULL);
从列表中删除元素(当然你必须删除它)
要使用deleteElement
函数,您需要将其更改为遍历列表(伪代码):
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
}