Jan 16, 2020 at 7:53pm UTC
Could you please help me in coding a linked list that can sort at the time of inserting an item in c++
#include <iostream>
using namespace std;
struct listItem
{
int data;
struct listItem *next;
};
bool Initialize(listItem *head);
char menu();
void insertFirst(listItem *&head, listItem *&temp, int item);
void Insert(listItem *&head, listItem *&temp, int item);
void search(listItem *&head, listItem *&temp);
void deleteItem(listItem *&head, listItem *&temp);
void traverse(listItem *curr);
bool Initialize(listItem *head)
{
if(head == NULL)
return true;
else
return false;
}
char menu()
{
char choice;
cout<<"~~~~~~~~~~~~~~~~~~~~~~~~\n";
cout<<" Menu"<<endl;
cout<<" ........\n";
cout<<"1. Add an Item\n";
cout<<"2. Remove an Item\n";
cout<<"3. Search an Item\n";
cout<<"4. Traverse an Item\n";
cout<<"5. Exit\n";
cout<<"~~~~~~~~~~~~~~~~~~~~~~~~\n";
cin>>choice;
return choice;
}
void Insert(listItem *&head, listItem *&temp, int item)
{
listItem *curr = new listItem;
if(head == NULL)
{
curr->data = item;`enter code here`
curr->next =NULL;
temp = curr;
head = curr;
}
else if(head->data > item)
{
curr->data = item;
curr->next = temp->next;
temp = curr;
}
else if(head->data < item && curr->next != NULL)
{
while (curr->data < item)
curr = curr->next;
temp->next = curr;
curr->data = item;
curr->next = temp;
temp = curr;
}
else if(head->data < item)
{
while(head->data < item && curr->next == NULL)
curr = curr->next;
curr->data = item;
curr->next = NULL;
temp = curr;
}
else
cout<<item<<" is already there!!!\n";
}
void search(listItem *&head, listItem *&temp)
{
cout<<"NO code for searching item"<<endl;
}
void deleteItem(listItem *&head, listItem *&temp)
{
if(Initialize(head))
cout<<"The list is already Empty\n";
else if(head == temp)
{
delete head;
head = NULL;
temp = NULL;
}
else
{
listItem *curr = new listItem;
head = head->next;
delete curr;
}
}
void traverse(listItem *curr)
{
if(Initialize(curr))
cout<<"The list is already Empty\n";
else
{
cout<<"The list contains:\n";
while(curr != NULL)
{
cout<<curr->data<<endl;
curr = curr->next;
}
}
}
int main()
{
listItem *head = NULL;
listItem *temp = NULL;
char choice;
int item;
do
{
choice = menu();
switch(choice)
{
case '1': cout<<"Please enter a number :";
cin>>item;
Insert(head, temp, item);
break;
case '2': //cout<<"Enter a number to delete :";
//cin>>item;
deleteItem(head, temp);
break;
case '3': search(head, temp);
break;
case '4': traverse(head);
break;
default: cout<<"System exit\n";
}
}while(choice != '5');
return 0;
}
Jan 16, 2020 at 7:57pm UTC
What do you need help with? It seems that you have an insert function that is at least trying to insert something in order.
Edit: Properly using code tags when posting code will go a long way in your effort to get help.
Last edited on Jan 16, 2020 at 7:58pm UTC