So I have an assignment where I\'m giving a random list of number and I need to sort them using insertion sort. I must use a singly linked list. I looked around at other posts b
I have coded it using classes instead of struct. Changes could be done but the algorithm would be same. Code for creating class of node and single link list..
#include
using namespace std;
class node{
public:
int data;
node* next;
};
class list{
node* head;
public:
list() {
head=NULL;
}
void add(int el) {
node* newNode=new node();
newNode->data=el;
newNode->next=NULL;
if(head==NULL) {
head=newNode;
} else {
node* temp=head;
while(temp->next!=NULL) {
temp=temp->next;
}
temp->next=newNode;
}
}
//Insertion sort code
void insertionSort() {
node* i=head->next;
while (i!=NULL)
{
node* key=i;
node* j=head;
while (j!=i)
{
if (key->datadata)
{
int temp=key->data;
key->data=j->data;
j->data=temp;
}
j=j->next;
}
i=i->next;
}
}
void display() {
node* temp=head;
while (temp!=NULL) {
cout<data<<" ";
temp=temp->next;
}
}
};
For creating main:
int main()
{
list l;
l.add(2);
l.add(6);
l.add(0);
l.add(3);
l.add(7);
l.add(4);
l.insertionSort();
l.display();
}
Do correct me if not working or the criteria for insertion sort in not implemented correctly.