我有这个C ++链接列表程序。该函数不调用insertAsFirstElement()
不知道为什么?
我在codeblocks中运行这个程序。
我从youtube获得了这个程序,上传者正在使用visual studio来完成这个程序。
我无法解决此问题,如果程序不正确,请在发现任何错误的地方进行更改。
感谢。
#include <iostream>
using namespace std;
struct node
{
int number;
node *next;
};
bool isEmpty(node *head);
char menu();
void insertAsFirstElement(node *&head, node *&last, int number);
void insert(node *&head, node *&last, int number);
void remove(node *&head, node *&last);
void showList(node *current);
bool isEmpty(node *head)
{
if (head == NULL)
return true;
else
return false;
}
char menu()
{
char choice;
cout << "Menu\n";
cout << "1. Add an item.\n";
cout << "2. Remove an item.\n";
cout << "3. Show an item.\n";
cout << "4. Exit\n";
cin >> choice;
return choice;
}
void insertAsFirstElement(node *&head, node *&last, int number)
{
node *temp = new node;
temp->number = number;
temp->next = NULL;
head = temp;
last = temp;
}
void insert(node *&head, node *&last, int number)
{
if(isEmpty(head))
{
insertAsFirstElement(head,last,number);
cout << "Hello I am here!!\n";
}
else
{
node *temp = new node;
temp->number = number;
temp->next = NULL;
last->next = temp;
last = temp;
}
}
void remove(node *&head, node *&last)
{
if(isEmpty(head))
cout << "The list is already empty.\n";
else if (head == last)
{
delete head;
head == NULL;
last == NULL;
}
else
{
node *temp = head;
head = head->next;
delete temp;
}
}
void showList(node *current)
{
if(isEmpty(current))
cout << "The list is empty\n";
else
{
cout << "The List contains:\n";
while(current != NULL)
{
cout << current->number << endl;
current = current->next;
}
}
}
int main()
{
node *head = NULL;
node *last = NULL;
char choice;
int number;
choice = menu();
cout<< choice;
do {
switch(choice)
{
case '1': cout << "Please Enter the number:";
cin >> number;
insert(head,last,number);
break;
case '2': cout << "Will Remove the number:" ;
remove(head,last);
break;
case '3' : cout << "Showing The Linked List:\n";
showList(head);
break;
default: cout << "System exit\n";
}
}while ( choice != '4');
return 0;
}
答案 0 :(得分:1)
你的行为... while循环需要不断询问用户的选择,这里有一个改变:
do {
choice = menu();
cout<< choice;
switch(choice)
{
case '1': cout << "Please Enter the number:";
cin >> number;
insert(head,last,number);
break;
case '2': cout << "Will Remove the number:" ;
remove(head,last);
break;
case '3' : cout << "Showing The Linked List:\n";
showList(head);
break;
default: cout << "System exit\n";
}
}while ( choice != '4');
希望有所帮助