No, this is nothing like the linked list question a few posts down :)
We just learned about linked lists in class, and I'm having some fun with them. I've got an append and an insert function working, but before I move onto a sort, I must get a swap function working.
(head is the start of the linked list, set to NULL in the constructor)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
|
template <class T> void LinkedList<T>::swap(unsigned int startPos, unsigned int endPos){
cout << endl;
if (!head || startPos == endPos) return;
if (startPos > endPos){
unsigned int store = startPos;
startPos = endPos;
endPos = store;
}
// I've got to make sure endPos isn't out of bounds here
Node<T> *beforeEnd = nodeAt(endPos - 1);
Node<T> *end = beforeEnd->next;
Node<T> *store = end->next;
Node<T> *start = nodeAt(startPos);
if (startPos == 0){
cout << "0 Size: " << size(); cin.get();
end->next = head->next;
head->next = store;
beforeEnd->next =head;
head = end;
}
else {
cout << "Size: " << size(); cin.get();
Node<T> *beforeStart = nodeAt(startPos - 1);
end->next = start->next;
start->next = store;
beforeStart->next = end;
beforeEnd->next = start;
}
return;
}
|
This code seems to be working, and I'm trying to condense the if/else statement a little. The goal is to try to remove "head" from the function to bring something out of being conditional. Line 25 is causing problems. The if statement works if it reads:
1 2 3 4 5 6 7
|
if (startPos == 0){
cout << "0 Size: " << size(); cin.get();
end->next = start->next;
start->next = store;
beforeEnd->next = start;
head = end;
}
|
Line 6 can not be
start = end
, it seems something goes out of scope and I loose the nodes before it. start
should be head anyway, so what gives? Thanks
Okay, going further, it seems like
Node<T> *start = nodeAt(startPos);
, doesn't quite get me the head. For example,
1 2
|
Node<T> *start = nodeAt(startPos);
end->next = start->next;
|
causes issues.