I am writing a program to create a linked list or chars and have them places in ascending order but I can;t seem to get it to into ascending order. It seems all jumbled up and i cant figure out where I am messing up. Here is the insert function:
I rewrote the section that checked tail first and placed it after my last while loop but still got the same issue. I believe my error is in the last else statement because the first and last nodes look like they get implemented properly because A (or whatever is smaller) is always first and F (or whatever is greater) is always last.
the while seems wrong.
say you have a list of 1,3,5,7 and get 4.
its not empty, it doesnt go after tail, and its not in front of head.
4 isnt less than 1, so the while loop is skipped.
then it inserts in a weird place...
@Enoizat yes thats correct. I meant it to be > instead because i test the < condition before.
@jonin yes i do agree thats whats happening. After changing the above mentioned code I'm getting this output after inserting abcfed (in that order).
a b c f
It appears e and d fail to get inserted.
@dhayden Yes. That was my intention. I only want the first Node's prev = nullptr. I encountered the error of not having any nodes point to prev so i need to fix that.
To clarify it's actually a doubly linked circular linked list where the last node point to the first node (or head)
int
DCList::insert(char c)
{
std::cout << "Insert Function. Inserting: " << c << std::endl;
//Create new Node
Node *newNode = new Node;
newNode->c = c;
newNode->next = nullptr;
newNode->prev = nullptr;
// Set "after" to the node that be after the new one, or NULL
// if the new node goes at the end
Node *after;
for (after = head; after ;after = after->next) {
if (newNode->c < after->c) {
break;
}
}
// Link it in
newNode->next = after;
if (after) {
newNode->prev = after->prev;
after->prev = newNode;
} else {
newNode->prev = tail;
tail = newNode;
}
if (newNode->prev) {
newNode->prev->next = newNode;
} else {
head = newNode;
}
return 0;
}
void
DCList::print(std::ostream &os)
{
for (Node *cur = head; cur; cur = cur->next) {
os << cur->c << ' ';
}
}