我有一个程序应该询问用户他们希望删除哪个项目。然后删除功能应该成功删除该节点。我知道我需要从前一个节点中获取地址,并使其指向我要删除的节点之后的节点,然后删除悬空节点。我在理解使它起作用的语法时遇到了一些困难。这是我的代码。我省略了不必要的功能。
#include <iostream>
#include <cstddef>
#include <string>
using namespace std;
struct Node
{
string item;
int count;
Node *link;
};
typedef Node* NodePtr;
void insert(NodePtr after_me, string an_item, int a_number);
void list_remove(NodePtr& head, string an_item);
void head_insert(NodePtr& head, string an_item, int a_number);
void show_list(NodePtr& head);
NodePtr search(NodePtr head, string target);
int main()
{
string new_item, target, remove_item;
int new_count;
NodePtr head = NULL;
head_insert(head, "Tea", 2);
head_insert(head, "Jam", 3);
head_insert(head, "Rolls", 10);
cout << "List contains:" << endl;
show_list(head);
NodePtr after_me = head;
after_me = after_me ->link;
cout << "Enter the item you wish to remove (string) \n";
cin >> remove_item;
after_me = search(head, remove_item);
if(after_me != NULL)
{
cout << "\nWill remove " << remove_item << endl << endl;
list_remove(head, remove_item);
cout << "List now contains:" << endl;
show_list(head);
}
else
{
cout << "I can't find " << remove_item
<< " in the list, so I can't remove anything \n";
}
system("PAUSE");
return EXIT_SUCCESS;
}
void list_remove(NodePtr& head, string remove_item)
{
NodePtr remove_ptr; //pointer to the node that is being removed
remove_ptr = search(head, remove_item); // finds the address for the item
// that is being removed and puts it
// in remove_ptr
}
// Uses cstddef:
void head_insert(NodePtr& head, string an_item, int a_number)
{
NodePtr temp_ptr;
temp_ptr = new Node;
temp_ptr -> item = an_item;
temp_ptr -> count = a_number;
temp_ptr->link = head;
head = temp_ptr;
}
//Uses iostream and cstddef:
void show_list(NodePtr& head)
{
NodePtr here = head;
while (here != NULL)
{
cout << here-> item << "\t";
cout << here-> count << endl;
here = here->link;
}
}
NodePtr search(NodePtr head, string target)
{
// Point to the head node
NodePtr here = head;
// If the list is empty nothing to search
if (here == NULL)
{
return NULL;
}
// Search for the item
else
{
// while you have still items and you haven't found the target yet
while (here-> item != target && here->link != NULL)
here = here->link;
// Found the target, return the pointer at that location
if (here-> item == target)
return here;
// Search unsuccessful, return Null
else
return NULL;
}
}