2013-10-25 82 views
2

嗨我試圖刪除鏈接列表中的節點。我首先試驗如何刪除頭部和尾部節點。頭部刪除似乎可行,但刪除後的尾部不會。當我運行代碼時,尾部曾經的位置被垃圾值替換。任何人都可以找出原因嗎?非常感謝!未來要刪除刪除鏈接列表中的節點

回答

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; 
+0

非常感謝你! – user1816546

0

保持一個節點你的尾巴和頭指針是一樣的嗎?你不檢查它。因此你可能會刪除你認爲是Head的指針,這也是一個尾巴。另外,如果它的下一個頭部或尾部是什麼?

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; 
} 
+1

你能解釋一點好嗎? – user1816546

+0

他的意思是,如果你想刪除節點3,你必須遍歷鏈表到節點2,然後去節點3,刪除他並繼續到節點4.現在你必須將節點2的地址保存到前一個地址節點4(如果列表是雙鏈接的)和節點4到節點2的下一個地址。 – andreashager

+0

好的,謝謝,我會看看如果我可以嘗試合併 – user1816546

0

如果什麼節點

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

+0

新條件不起作用,程序仍然崩潰並打印垃圾值曾經是尾巴。我已經安排了goto del,謝謝你的提示! – user1816546

+0

@ user1816546我編輯了我的答案 –

+0

非常感謝您的幫助,但是我在您之前看到了MAG用戶的答案。如果可以的話,我會回答兩個正確的答案! – user1816546