我已经看过这个话题的其他线程,但没有能够使用它们来解决我的问题。从双向链表中删除一个节点
这是在链接列表中的节点的主类定义:
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