#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int data;
Node* next;
};
void sortInsert(Node** head_ref,
Node* new_node)
{
Node* curr;
if (*head_ref == NULL
|| (*head_ref)->data
>= new_node->data) {
new_node->next = *head_ref;
*head_ref = new_node;
}
else {
curr = *head_ref;
while (curr->next != NULL
&& curr->next->data
< new_node->data) {
curr = curr->next;
}
new_node->next = curr->next;
curr->next = new_node;
}
}
Node* newNode(int new_data)
{
Node* new_node = new Node();
new_node->data = new_data;
new_node->next = NULL;
return new_node;
}
void displayList(Node* head)
{
Node* temp = head;
while (temp != NULL) {
cout << temp->data << " ";
temp = temp->next;
}
}
int main()
{
Node* head = NULL;
Node* newN = newNode(5);
sortInsert(&head, newN);
newN = newNode(20);
sortInsert(&head, newN);
newN = newNode(17);
sortInsert(&head, newN);
newN = newNode(13);
sortInsert(&head, newN);
newN = newNode(11);
sortInsert(&head, newN);
newN = newNode(19);
sortInsert(&head, newN);
cout << "Created Linked List\n";
displayList(head);
return 0;
}
Comments
Leave a comment