嗨,我正在尝试删除链表中的节点。我首先正在尝试如何删除头部和尾部节点。头部删除似乎有效,但删除的尾部不起作用。当我运行代码时,尾巴曾经所在的地方被替换为垃圾值。谁能弄清楚为什么?非常感谢!
void CList :: Remove() {
int data = NULL;
std::cout<<"Enter value you wish to remove ";
std:: cin>> data;
cNode *pMyPointer = m_pHead;
while (pMyPointer != NULL)
{
if (pMyPointer->m_nValue == data) {
std::cout << "Element found";
goto del;
}
else {
pMyPointer = pMyPointer->m_pNext;
}
}
del:
//removing the head
if (pMyPointer == m_pHead)
m_pHead= m_pHead->m_pNext;
//removing the tail
else if (pMyPointer == m_pTail)
m_pTail = m_pTail->m_pPrev;
delete pMyPointer;
}
考虑node_1点到node_2(只是一个 2 节点的情况)看看这个代码
else if (pMyPointer == m_pTail)
m_pTail = m_pTail->m_pPrev;
node_1指向node_2。它仍然指向那里.删除node_2后,node_1仍将指向node_2(或删除node_2后为垃圾),因此必须确保node_1指向NULL。即最后,但应该指向空。
类似的东西
else if (pMyPointer == m_pTail)
m_pTail->m_pPrev->next=NULL;
m_pTail = m_pTail->m_pPrev;
用这个语句
while (pMyPointer != NULL)
您的指针在退出循环时可能指向 NULL,因此它将跳过尾部指针。
而是尝试
while (pMyPointer->m_pNext != NULL)
还需要使倒数第二个节点指向 NULL。
else if (pMyPointer == m_pTail) {
m_pTail = m_pTail->m_pPrev;
m_pTail->m_pNext = NULL;
}
delete pMyPointer;
另外,不要goto del
,只需使用break;
在要删除的节点之前保留一个节点
如果你的尾巴和头部指针相同怎么办?你不检查它。因此,您可能会删除您认为是头部的指针,这也是一个尾部。另外,如果它是下一个是正面或上一个尾部怎么办?
void CList :: Remove() {
int data = NULL;
std::cout<<"Enter value you wish to remove ";
std:: cin>> data;
cNode *pMyPointer = m_pHead;
while (pMyPointer != NULL)
{
if (pMyPointer->m_nValue == data) {
std::cout << "Element found";
goto del;
}
else {
pMyPointer = pMyPointer->m_pNext;
}
}
del:
//taking care of the neighbors
if (pMyPointer->m_pPrev)
pMyPointer->m_pPrev->m_pNext = pMyPointer->m_pNext;
if (pMyPointer->m_pNext)
pMyPointer->m_pNext->m_pPrev = pMyPointer->m_pPrev;
// removing the head
if (pMyPointer == m_pHead)
m_pHead= m_pHead->m_pNext;
//removing the tail
if (pMyPointer == m_pTail)
m_pTail = m_pTail->m_pPrev;
delete pMyPointer;
}