Write a C++ code to ask the user to enter 4 values (whole numbers). Your code should print the numbers in descending order. (Don't solve using array)
In the below code,
1. Take 4 whole numbers as input.
2. Insert these 4 values in the linked list(array cannot be used as directed in the question) as an individual node.
3.Sort the numbers in descending order using insertion sort.
#include<iostream>
using namespace std;
// Link list node
struct Node
{
int data;
struct Node* next;
};
// Function to insert a given node in a reverse sorted linked list
void descendingSort(struct Node**, struct Node*);
// function to sort a singly linked list
void insertAtPosition(struct Node **head_ref)
{
// Initialize sorted linked list
struct Node *sorted = NULL;
// Traverse the given linked list and insert every node to be sorted
struct Node *current = *head_ref;
while (current != NULL)
{
// Store next for next iteration
struct Node *next = current->next;
// insert current in sorted linked list
descendingSort(&sorted, current);
// Update current
current = next;
}
// Update head_ref to point to sorted linked list
*head_ref = sorted;
}
// function to insert a new_node in a list.
void descendingSort(struct Node** head_ref, struct Node* new_node)
{
struct Node* current;
/* Special case for the head end */
if (*head_ref == NULL || (*head_ref)->data <= new_node->data)
{
new_node->next = *head_ref;
*head_ref = new_node;
}
else
{
/* Locate the node before the point of insertion */
current = *head_ref;
while (current->next!=NULL &&
current->next->data > new_node->data)
{
current = current->next;
}
new_node->next = current->next;
current->next = new_node;
}
}
// Function to print linked list
void printList(struct Node *head)
{
struct Node *temp = head;
while(temp != NULL)
{
cout<<temp->data<<" ";
temp = temp->next;
}
}
// A function to insert a node at the beginning of linked list
void push(struct Node** head_ref, int new_data)
{
/* allocate node */
struct Node* new_node = new Node;
/* put in the data */
new_node->data = new_data;
/* link the old list off the new node */
new_node->next = (*head_ref);
/* move the head to point to the new node */
(*head_ref) = new_node;
}
int main()
{
struct Node *a = NULL;
int w,x,y,z;
cin>>w>>x>>y>>z;
push(&a, w);
push(&a, x);
push(&a, y);
push(&a, z);
cout<<"Linked List before sorting \n";
printList(a);
insertAtPosition(&a);
cout<<"\nLinked List after sorting \n";
printList(a);
return 0;
}
OUTPUT :
Get Answers For Free
Most questions answered within 1 hours.