编写程序以使用双链表。它的类完美地工作,一切都正确存储,节点正在被添加,显示和搜索。问题是删除。该类的代码和deleteNode方法如下所示,在我的生命中,我似乎无法弄清楚它为什么不删除正确的节点。
例如,假设我插入一个包含数据的节点" Morgan Captain 666-666-6666"到我链接列表的末尾,当我显示它和所有内容时,一切都会出现。我对这些方法没有任何问题。但是,当我尝试删除编号为" 666-666-6666的节点时,"我被提出了我的"号码不存在"消息。
我已经绘制了我的链表图表,对我来说这是有道理的,但在代码中显然不是这样。有什么指针吗?
编辑:我在列表末尾有一个案例可以使用,但是没有为列表的开头和中间条目做任何事情。头节点也被作为所有不必要函数的参数取出。更新后的代码如下。编辑2:似乎最后一种情况不适用于从读入函数添加到内存的节点。更新。
类和结构:
struct node{
node* next;
node* prev;
string lastname;
string firstname;
string phnum;
};
class linkedList
{
node* n; // indicator of current node
node* head; // head node, does change as needed
public:
linkedList();
~linkedList();
void choice(char choice);
void makeList(node* &head);
void addNode();
void deleteNode();
void searchName();
void searchNum();
void displayList();
void writeFile();
};
deleteNode方法:
void linkedList::deleteNode()
{
string num;
node *p, *f; // To link any nodes back together after deletion.
n = head;
// Displays list of nodes to reference. Function deletes based on phone number string comparison.
displayList();
cout << "Please enter the phone number from the list above, as displayed, that you would like to delete: ";
cin >> num;
while (n != NULL)
{
// If a number matches
if (n->phnum == num)
{
// If it's the head node - DOES NOT WORK
if (n == head)
{
head = head->next;
head->prev = NULL;
delete n;
cout << "This name and number has been deleted." << endl << endl;
return;
}
// if it's a middle node - DOES NOT WORK
else if (n->next != NULL)
{
p = n->prev;
f = n->next;
p->next = f;
f->prev = p;
delete n;
cout << "This name and number has been deleted." << endl << endl;
return;
}
// If it's an end node - WORKS FOR ADDED NODES, NOT DEFAULT ONES
else
{
n->prev->next = NULL;
delete n;
cout << "This name and number has been deleted." << endl << endl;
return;
}
}
//If there is no matching number
else
n = n->next;
}
cout << "This number does not exist in our system." << endl << endl;
return;
}
答案 0 :(得分:0)
您只处理了正确删除“中间”元素的一般情况。您必须考虑要删除第一个或最后一个元素的情况,确定识别这些情况的“if”条件,并使用不同的删除代码来适应。一个提示是,正如你所做的那样,将* head传递给删除例程将不会在所有情况下都有效。我不会更明确,所以你可以继续学习。