Run
#include<iostream> //haeder files
using namespace std;
// create node
struct Node {
int data;
struct Node *next;
};
// this function for insert the new node in linked list
void sortedInsert(struct Node** head_ref, struct Node* new_node){
struct Node* present = *head_ref;
// Case 1 when list is empty
if (present == NULL){
new_node->next = new_node;
*head_ref = new_node;
}
// Case 2 when the node insert before the head
else if (present->data >= new_node->data){
//when value is smaller than head's value
while( present->next != *head_ref)
present = present->next;
present->next = new_node;
new_node->next = *head_ref;
*head_ref = new_node;
}
// Case 3 when node insert in after head in somewhere
else{
//Locate the node before the point of insertion
while ( present->next!= *head_ref && present->next->data < new_node->data)
present = present->next;
new_node->next =present->next;
present->next = new_node;
}
}
//this Function to print nodes in a given linked list
void printList(struct Node *start) {
struct Node *temp;
if(start != NULL){
temp = start;
cout<<"\n";
do {
cout<<temp->data<<" ";
temp = temp->next;
} while(temp != start);
}
}
// main method start
int main(){
int arr[] = {12, 56, 2, 11, 1, 90};
int list_size, i;
// start with empty linked list
struct Node *start = NULL;
struct Node *temp;
// Create linked list from the array arr[].
// Created linked list will be 1->2->11->12->56->90
for (i = 0; i< 6; i++) {
temp = (struct Node *)malloc(sizeof(struct Node));
temp->data = arr[i];
sortedInsert(&start, temp);
}
printList(start);
return 0;
}
Login/Signup to comment