2

您好我正在尝试删除链表中的节点。我首先尝试如何删除头部和尾部节点。头部删除似乎有效,但删除的尾部却没有。当我运行代码时,尾巴的位置被替换为垃圾值。谁能弄清楚为什么?非常感谢!

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;
}
4

4 回答 4

2

考虑 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 。即最后但一个应该指向 null 。

就像是

else if (pMyPointer == m_pTail)
    m_pTail->m_pPrev->next=NULL;
    m_pTail = m_pTail->m_pPrev;
于 2013-10-25T11:23:58.623 回答
1

有了这个声明

 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;

于 2013-10-25T11:16:11.833 回答
0

Stay one node ahead of the node you want to delete

于 2013-10-25T11:05:55.423 回答
0

如果你的尾指针和头指针相同怎么办?你不检查它。因此,您可能正在删除您认为是 Head 的指针,它也是 Tail。另外,如果它是头部的 Next 或尾部的 Prev 怎么办?

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;
}
于 2013-10-25T11:07:07.130 回答