我已經看過這個話題的其他線程,但沒有能夠使用它們來解決我的問題。從雙向鏈表中刪除一個節點
這是在鏈接列表中的節點的主類定義:
class node {
public:
// default constructor
node() {name = ""; prev = NULL; next = NULL;};
// default overloaded
node(string s) {name = s; prev = NULL; next = NULL;};
// item in the list
string name;
// links to prev and next node in the list
node * next, * prev;
};
以上是節點類的定義,這是在其產生鏈表另一類使用。鏈表代碼給了我們,我們必須修改,所以我知道它的工作原理。我已經完成並測試了雙向鏈表中新增節點的工作,現在我正在從這個雙向鏈表中刪除節點。
功能刪除一個節點:http://pastebin.com/HAbNRM5W
^這是我需要幫助的代碼中,有太多的重複鍵入
我被我的老師告訴記者,該代碼,問題是行56,它讀取:
tmp->prev = prev;
我想設置鏈接到前一個節點是正確的。我嘗試使用類似的if/else
循環的情況是當前節點是否是列表中的最後一項。如果它是最後一項(又名curr->next = NULL
),則不要使用curr->next
設置鏈接並停止循環迭代。
任何幫助/想法/建議/反饋將不勝感激!
void linkedList::remove(string s)
{
bool found = false;
node * curr = getTop(), * prev = NULL;
node * tmp = new node();
while(curr != NULL)
{
// match found, delete
if(curr->name == s)
{
found = true;
// found at top
if(prev == NULL)
{
node * temp = getTop();
setTop(curr->next);
getTop()->prev = NULL;
delete(temp);
} // end if
else
{
// determine if last item in the list
if (curr->next = NULL)
{
// prev node points to next node
prev->next = curr->next;
// delete the current node
delete(curr);
} // end if
// if not last item in list, proceed as normal
else
{
// prev node points to next node
prev->next = curr->next;
// set the next node to its own name
tmp = prev->next;
// set prev-link of next node to the previous node (aka node before deleted)
tmp->prev = prev;
// delete the current node
delete(curr);
} // end else
} // end else
} // end if
// not found, advance pointers
if(!found)
{
prev = curr;
curr = curr->next;
} // end if
// found, exit loop
else curr = NULL;
} // end while
if(found)
cout << "Deleted " << s << endl;
else
cout << s << " Not Found "<< endl;
} // end remove
你問的問題到底是什麼? –
zac,我需要此方法來刪除C++中的雙向鏈表的節點。我的講師告訴我「tmp-> prev = prev;」是NULL,如果我修復這一行,代碼/程序應該工作。我無法弄清楚什麼是空/爲什麼它是空的,以便我可以修復它。謝謝。 – user2766542
在你正在進行刪除的地方,對prev,curr和curr-> next(if!null)中的每一個執行打印命名可能是一個好主意。 可以方便地分揀指針混淆。 – RichardPlunkett