In: Computer Science
IN C++.
Objective: Create a Singly linked list of numbers based upon user input. Program logic: Ask for a number, add that number to the front of the list, print the list. Repeat until they enter -1 for the number. . Sample Input: 10, 15, 5, 2, 4, -1 Output: 4, 2, 5, 15, 10.
Next sort all the numbers using selection sort and display them. Next give the user option to search for a specific number in the list. If the user desired number exist output "the number you entered exists" else output "this number does not exist".
Next ask user if they want to delete a specific number. Delete and display an appropriate message. If the user specified number does not exist display an appropriate message.
Don't use class. Structs and nodes only
Code
#include<iostream>
using namespace std;
void sorted_ins(struct Node **,struct Node *);
struct Node
{
int value;
struct Node *next;
};
struct Node *head=NULL;
void add(struct Node **head,int v)
{
struct Node *node = new Node;
node->value=v;
node->next=*head;
*head=node;
}
void selection_sort(struct Node **head)
{
struct Node* temp = *head;
while(temp)
{
struct Node* min = temp;
struct Node* r = temp->next;
while(r)
{
if(min->value > r->value)
min = r;
r = r->next;
}
int x = temp->value;
temp->value= min->value;
min->value= x;
temp = temp->next;
}
}
void del(struct Node **head,int d)
{
struct Node *current=NULL;
struct Node *prev=NULL;
if((*head)->value != d && (*head)->next == NULL)
{
printf("%d not found in the list\n", d);
return;
}
current=*head;
while(current->next != NULL && current->value != d)
{
prev = current;
current = current->next;
}
if(current->value == d)
{
prev->next = prev->next->next;
cout<<d<<" has been deleted successfully";
free(current);
}
else
printf("%d not found in the list.", d);
}
void search(struct Node** head,int v)
{
struct Node *current=*head;
while(current!=NULL)
{
if(current->value == v)
{
printf("the number you entered exists\n");
return;
}
current = current->next;
}
printf("the number you entered does not exist",v);
}
void print(struct Node** head)
{
struct Node * temp=*head;
while(temp!=NULL)
{
printf("%d ",temp->value);
temp=temp->next;
}
}
int main()
{
struct Node *s=NULL;
int d;
while(1) //store value to list till -1 entered
{
cin>>d;
if(d==-1)
break;
add(&s,d);
}
cout<<"inserted elements \n";
print(&s);
selection_sort(&s);
cout<<"\nelements after sort\n";
print(&s);
cout<<"\nenter a number to search\n";
cin>>d;
search(&s,d); //search the element
cout<<"enter a number to delete\n";
cin>>d;
del(&s,d); //delete the element
cout<<"\nelememts after deletion\n";
print(&s);
return 0;
}
Terminal Work
.