Hello;
I have little experience in c++ and I should implement insertion sort algorithm using linked list. I wrote a working code however I should have use friends for having the list elements from a seperate class and use templates for sorting arbitrary data elements. Can anybody help me how to use friends and templates??
Here is my code:
#include <iostream.h>
#include <stdlib.h>
struct listNode
{
int data;
listNode * next;
};
void enterList ( listNode *& );
void sortList ( listNode *& );
void printList ( listNode * );
#define test(n) if ( n == NULL ) exit ( 1 );
int main ()
{
listNode * front = NULL;
enterList ( front );
sortList ( front );
printList ( front );
system("PAUSE");
return 0;
}
void enterList ( listNode *& l )
{
cout << "Enter your list " <<endl;
int d;
char ch;
listNode * c = NULL; //current node
do
{
cout << "Enter a number: " ;
cin >> d;
if ( l == NULL )
{
l = new listNode;
test(l)
l -> data = d ;
l -> next = NULL;
c = l;
}
else
{
c -> next = new listNode;
test(c->next)
c = c -> next;
c -> data = d;
c -> next = NULL;
}
cout << "Enter another ( y or n )? " ;
cin >> ch;
}while ( ch != 'n' );
}
void sortList ( listNode *& l )
{
listNode * t = NULL; //temporary
listNode * s = NULL; //sorted list
listNode * f = NULL; //follower node
listNode * st = NULL;
while ( l != NULL )
{
t = l;
l = l -> next;
t -> next = NULL;
if ( s == NULL )
s = t;
else
{
if ( s -> data > t -> data )
{
t -> next = s;
s = t;
}
else
{
f = s;
st = s -> next;
while ( st != NULL )
{
if ( st -> data > t -> data )
break;
f = st;
st = st -> next;
}
f -> next = t;
t -> next = st;
}
}
}
l = s;
}
void printList ( listNode * p )
{
int x = 1;
while ( p != NULL )
{
cout << x << "-)" << p -> data << endl;
p = p -> next;
x++;
}
}