Creating sorted Linklist
Jump into the code directly :
#include <iostream>
#include <conio.h>
using namespace std;
struct node {
int data;
node *next;
node(int val, node *nextval)
{
data = val;
next = nextval;
}
};
void insertSortedValue(node **head, int val)
{
node *start = *head;
node *newNode = new node(val, start);
if (start == NULL || start->data >= val)
{
newNode->next = start;
*head = newNode;
}
else
{
while (start->next != NULL && start->data < val)
{
start = start->next;
}
newNode->next = start->next;
start->next = newNode;
}
}
void printNode(node *head)
{
if (head == NULL)
{
cout << "Empty List" << endl;
return;
}
while (head->next != NULL)
{
cout << head->data << endl;
head = head->next;
}
}
void main()
{
node *head = NULL;
printNode(head);
insertSortedValue(&head, 5);
insertSortedValue(&head, 4);
insertSortedValue(&head, 9);
insertSortedValue(&head, 3);
insertSortedValue(&head, 8);
printNode(head);
_getch();
}
Comments
Post a Comment