我能夠成功地將名稱添加到列表的末尾,但我無法將其添加到前面。 我想弄清楚如何添加到節點的前面,謝謝。 我以爲我明白,要加到後面,你用最後一個屁股變量的代碼將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