What I'm trying to do it create a program that generates 500,000 random first names, last names, and id numbers. Then put them in a linked list, and sort them. I've decided to use the merge sort because of the large amount of data.
when just appending nodes, the code take 1.5 hours just to append. how can i change my appendNode function to increase the speed of this program?
CODE
#ifndef LINKEDLIST_H
#define LINKEDLIST_H
#include <iostream>
using namespace std;
class LinkedList
{
private:
class ListNode
{
friend class LinkedList;
string fname;
string lname;
int id;
ListNode *next;
ListNode(string fname1, string lname1, int id1, ListNode *next1 = NULL)
{
fname = fname1;
lname = lname1;
id = id1;
next = next1;
}
};
ListNode *head;
public:
LinkedList()
{head=NULL;}
~LinkedList();
void appendNode(string, string, int);
};
void LinkedList::appendNode(string fname, string lname, int id)
{
if(head==NULL)
head=new ListNode(fname, lname, id);
else
{
ListNode *nodePtr;
nodePtr = head;
while (nodePtr->next != NULL)
nodePtr = nodePtr->next;
nodePtr->next = new ListNode(fname, lname, id);
}
}
LinkedList::~LinkedList()
{
ListNode *nodePtr, *nextNodePtr;
nodePtr = head;
while(nodePtr != NULL)
{
nextNodePtr = nodePtr->next;
delete nodePtr;
nodePtr = nextNodePtr;
}
}
#endif
CODE
#include "linkedlist.h"
#include <stdlib.h>
#include <time.h>
#include <iomanip>
#include <cstdlib>
using namespace std;
void rword (char *word)
{
int len = rand () % 6 + 1;
word [len] = 0;
while (len) word [--len] = 'a' + rand () % 26;
}
int main ()
{
char word[7];
char word2[7];
int x=0;
srand(time(0));
LinkedList list;
while (x<=500000)
{
rword(word);
rword(word2);
list.appendNode(word, word2, x);
x++;
cout << "Node " << x << " inserted." << endl;
}
cout << "Program ready to sort." << endl;
}