Improved SimpleList

This commit is contained in:
Stefan Kremser
2018-04-12 19:58:54 +02:00
parent 71b35a746d
commit 6b585fddb4

View File

@@ -110,10 +110,10 @@ void SimpleList<T>::add(T obj){
if(!listBegin) if(!listBegin)
listBegin = node; listBegin = node;
if(!listEnd){ if(listEnd){
listEnd->next = node;
listEnd = node; listEnd = node;
} else { } else {
listEnd->next = node;
listEnd = node; listEnd = node;
} }
@@ -127,25 +127,17 @@ void SimpleList<T>::add(int index, T obj){
return; return;
} }
// Example: a -> c Node<T> *nodeNew = new Node<T>();
// we want to add b between a and c nodeNew->data = obj;
nodeNew->next = NULL;
Node<T>* nodeA = getNode(index); if(index == 0)
Node<T>* nodeC = nodeA ? nodeA->next : NULL; listBegin = nodeNew;
else{
Node<T> *nodeB = new Node<T>(); Node<T>* nodePrev = getNode(index - 1);
nodeB->data = obj; nodeNew->next = nodePrev->next;
nodeB->next = nodeC; nodePrev->next = nodeNew;
}
// a -> b -> c
if(nodeA)
nodeA->next = nodeB;
if(!nodeC)
listEnd = nodeB;
if(!listBegin)
listBegin = nodeB;
listSize++; listSize++;
} }
@@ -162,44 +154,18 @@ void SimpleList<T>::remove(int index){
if (index < 0 || index >= listSize) if (index < 0 || index >= listSize)
return; return;
Node<T>* nodeA = getNode(index - 1); // prev Node<T>* nodePrev = getNode(index - 1);
Node<T>* nodeB = getNode(index); // node to be deleted Node<T>* nodeToDelete = getNode(index);
Node<T>* nodeC = getNode(index + 1); // next
// a -> b -> c if(index == 0) {
if(nodeA && nodeC){ listBegin = nodeToDelete->next;
// a -> c } else {
nodeA->next = nodeC; nodePrev->next = nodeToDelete->next;
if(!nodePrev->next)
listEnd = nodePrev;
} }
// a -> b delete nodeToDelete;
else if(nodeA){
// a
nodeA->next = NULL;
listEnd = nodeA;
}
// b -> c
else if(nodeC){
// c
listBegin = nodeC;
}
// b
else{
listBegin = NULL;
listEnd = NULL;
}
if(listBegin == nodeB){
listBegin = nodeB->next;
}
if(listEnd == nodeB){
listEnd = getNode(listSize - 2);
}
delete(nodeB);
isCached = false; isCached = false;
@@ -350,26 +316,25 @@ void SimpleList<T>::swap(int x, int y){
template<typename T> template<typename T>
void SimpleList<T>::sort(bool (*cmp)(T &a, T &b)) { void SimpleList<T>::sort(bool (*cmp)(T &a, T &b)) {
// bubble sort because I'm lazy // bubble sort :D
// Example: a -> b -> c -> d
// we want to swap b with c when b.value > c.value
// and repeat that until the list is sorted
Node<T>* nodeA; Node<T>* nodeA;
Node<T>* nodeB; Node<T>* nodeB;
int c = listSize; int c = listSize-1;
bool swapped = true;
while(c--){ while(c > 0 && swapped){
for(int i = 1; i <= c; i++){ swapped = false;
nodeA = getNode(i - 1); for(int i = 0; i < c; i++){
nodeB = getNode(i); nodeA = getNode(i);
nodeB = getNode(i+1);
if(cmp(nodeA->data, nodeB->data)) { if(cmp(nodeA->data, nodeB->data)) {
swap(i-1,i); swap(i,i+1);
swapped = true;
} }
} }
c--;
} }
} }