I just learned about linked lists, so i decided to experiment a little. I'm trying to make a linked list that automatically keeps all of the data in consecutive order (like bubble sort built in :P).
Anyways, the problem is that while it adds data, the second thing added disappears, and IDK why :|
Here's the code:
sortlist.h
#ifndef SORTLIST_H_INCLUDED
#define SORTLIST_H_INCLUDED
template<typename T>
class sortlist {
public:
sortlist() { bottom = NULL; }
sortlist(typename T dataToAdd);
~sortlist() {}
void printall() { for(node* x = bottom; x->next != NULL;) { std::cout <<x->data<<"\n"; x = x->next; } }
void add(typename T dataToAdd);
private:
struct node { typename T data;
node* next;
} *bottom;
};
template<typename T>
sortlist<typename T>::sortlist(typename T dataToAdd) {
bottom = new node;
bottom->data = dataToAdd;
bottom->next = NULL;
}
template<typename T>
void sortlist<typename T>::add(typename T dataToAdd) {
// if list is empty
if(bottom == NULL) {
bottom = new node;
bottom->data = dataToAdd;
bottom->next = NULL;
}
// iterate shall we?
else {
node* iter = bottom;
while((iter->data < dataToAdd) && (iter->next != NULL)) {
iter = iter->next;
}
node* newdata = new node;
newdata->data = dataToAdd;
newdata->next = iter->next;
iter->next = newdata;
}
}
#endif // SORTLIST_H_INCLUDED
main.cpp
#include <iostream>
#include "sortlist.h"
using namespace std;
int main() {
sortlist<int> ll;
ll.add(34534);
ll.add(789);
ll.add(344);
ll.add(344);
ll.add(466);
ll.add(654);
ll.printall();
std::cin.get();
return 0;
}
anyone see what's wrong??? :?