Self-Sorting Linked List in C++

/*********************************************************************************************************
* Self Sorting Linked List *
* Programmer: Graham Nedelka *
* Created in May, 2013 *
* Computer Science 116: Data Structures *
*********************************************************************************************************/

#include <iostream>
#include <time.h>
#include <fstream>
#include <iomanip>
#include <vector>

using namespace std;

struct node{
int data;
node *next;
node *previous;
public:
node(int value){data = value; next = NULL; previous = NULL;};
};

class LL{
node *head;
node *tail;
public:
LL() {head = NULL;tail = NULL;};
void add(int number);
void show();
};

void LL::add(int value){
node *current = new node(value);
if (head == NULL){
tail = current;
head = current;
}
else{
node *temp = head;
node *temptail = tail;
if (value < temp->data){
node *temp2 = new node(value);
temp2->next = head;
head = temp2;
return;
}
while(temp->next != NULL){
if (value > temp->data and value < temp->next->data){
current->next = temp->next;
temp->next = current;
temp = temp->next;
}
else if (current->data > temptail->data){
temptail->next = current;
current->previous = temptail;
tail = temptail->next;
tail->previous = temptail;
}
temp = temp->next;
}
}
}

void LL::show(){

node *temp = head;
if (temp != NULL){
cout << temp->data << endl;
temp = temp->next;
while (temp != NULL){
cout << temp->data << endl;
temp = temp->next;
}
}

}

int main(){
srand(time(NULL));
LL ll;
vector<int> armstrongVector;
cout << “INITIALIZING NUMBER GENERATION OUTPUT TO FILE…\n” <<endl;
ofstream armstrong(“evaluation.armstrong”);
for (int i = 0; i < 100 + 1; ++i){
armstrong << rand() % 910000<<endl;
}
armstrong.close();
cout << “OUTPUT TO FILE COMPLETE.\n” <<endl;
ifstream readArmstrong;
readArmstrong.open(“evaluation.armstrong”);
int inputValue;
cout << “READING FILE…\n” <<endl;
while (!readArmstrong.eof()){
readArmstrong >> inputValue;
cout << inputValue << endl;
ll.add(inputValue);
}
readArmstrong.close();
cout << “\nFILE CLOSED.” <<endl;
cout << “\nNUMBERS STORED IN LINKED LIST, THEN SORTED INTERNALLY…\n” <<endl;
ll.show();
return 0;
}

Advertisements

Tags: , , ,

One response to “Self-Sorting Linked List in C++”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: