我能够成功地将名称添加到列表的末尾,但我无法将其添加到前面。 我想弄清楚如何添加到节点的前面,谢谢。 我以为我明白,要加到后面,你用最后一个屁股变量的代码将cout,所以我试图操纵,并使用头开始在开始。添加到链接列表的前面
#include <iostream>
#include <string>
using namespace std;
struct node
{
string name;
string name1;
node *next;
};
bool isEmpty(node *head);
char menu();
void insert(node *&head, node *&last, string name);
void insert_front(node *&head, node*&start, string name1);
void insert_back(node *&head, node *&last, string name);
void print(node *current);
bool isEmpty(node *head)
{
if (head == NULL)
return true;
else
return false;
}
char menu()
{
char choice;
cout << "Menu\n";
cout << "1. Add a name to the front of the list." << endl;
cout << "2. Add a name to the back of the list." << endl;
cout << "3. Print the list." << endl;
cout << "4. Exit." << endl;
cin >> choice;
return choice;
}
void insert(node *&head, node *&last, string name)
{
node *temp = new node;
temp->name = name;
temp->next = NULL;
head = temp;
last = temp;
}
void insert_back(node *&head, node *&last, string name)
{
if (isEmpty(head))
insert(head, last, name);
else
{
node *temp = new node;
temp->name = name;
temp->next = NULL;
last->next = temp;
last = temp;
}
}
void insert_front(node *&head, node *& start, string name1)
{
node *temp = new node;
temp->name1 = name1;
temp->next = head;
head = temp;
}
void print(node *current)
{
if (isEmpty(current))
cout << "The list is emtpy." << endl;
else
{
cout << "List of names: \n";
while (current != NULL)
{
cout << current->name << endl;
current = current->next;
}
}
}
int main()
{
node *head = NULL;
node *last = NULL;
node *start = NULL;
char choice;
string name, name1;
do
{
choice = menu();
switch (choice)
{
case '1':
cout << "Enter first name to the front of the list: " << endl;
cin >> name1;
insert_front(head, start, name1);
break;
case '2':
cout << "Enter first name to the end of the list:" << endl;
cin >> name;
insert_back(head, last, name);
break;
case '3': print(head);
break;
case '4':
return 0;
break;
}
} while (choice != 4);
}
提示:insert_back()应该就像insert_front()一样。除了前/后的东西。例如,对于空列表,insert_front()会做一些特殊的事情。显然,insert_back()应该执行相同的操作,因为如果列表为空,则insert_front()和insert_back()是相同的。事实上,你的insert_back()不这样做应该是你的第一个关于什么是错的喇叭线索。 –
你的'print'函数打印'current-> name',但你的'insert_front'方法只设置'name1'。 – 0x499602D2