我想弄清楚如何讓我的鏈接列表以數字順序顯示數值變量。我知道我需要設置另一個空白,但我迷失了,按數字順序設置。這裏是我的源代碼:鏈接列表:以C++的物理和邏輯順序顯示列表
#include <iostream>
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);
void showLogic(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 the list Physically.\n";
cout << "4. Show the list Logically.\n";
cout << "5. 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);
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;
}
}
}
void showLogic(node *current)
{
}
int main()
{
node *head = NULL;
node *last = NULL;
char choice;
int number;
do
{
choice = menu();
switch(choice)
{
case '1': cout << "Please enter a number: ";
cin >> number;
insert (head,last,number);
break;
case '2': remove(head,last);
break;
case '3': showList(head);
break;
case '4':
break;
default: cout << "System Exit\n";
}
}
while(choice != '5');
system ("pause");
return 0;
}
你將如何完成這個沒有排序?您需要以某種方式對列表進行排序。 – PaulMcKenzie
這就是爲什麼我要問如何在void showLogic(node * current)中對void showList(node * current)數值順序進行排序。 –
所以你的問題歸結爲「我如何排序鏈表」?我確定SO上有很多點擊。最簡單的方法是將列表中的數值複製到數組中,對數組進行排序並顯示數組。 – PaulMcKenzie