Last node in linked list not sorted

This works perfectly except the book that's supposed to go first (i.e. a book that starts with 'A') is at the end of the list.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
void inventory::insert_sorted(Node book) {
  Node *insert = new Node;

  insert->name = book.name;
  insert->price = book.price;
  insert->amount = book.amount;
  insert->ISBN = book.ISBN;
  insert->next = NULL;
  if(head == NULL)
    head = insert;
  else {
    Node *tail = head;
    while(tail->next != NULL) {

      if(tail->name.compare(tail->next->name) > 0) {
        string temp = tail->next->name;
        tail->next->name = tail->name;
        tail->name = temp;
      }
      tail = tail->next;
    }
    tail->next = insert;
  }
} 
One issue is that you are swapping just the name of the book, not the other properties. So now you're going to have mismatched name/isbn, for example.

What happens if you have [B, C] as your linked list, and you are trying to insert A, to make it [A, B, C]? When you enter your while loop, you are comparing B > C. But why? Are you not assuming that the linked list is already sorted? So my question is, should your 'inventory' always be sorted, or is there a 'insert (not sorted)' function as well?

Follow, line-by-line, what happens when you have [B, C] as your list, and you are adding A.
Long story short: As long as your list is already sorted, your while loop will just iterate to the last node, then your while loop will end, and tail->next = insert will be called. So your list will have [B, C, A]. Essentially, you're comparing the wrong thing in your if -statement on line 15.

First, I suggest renaming your 'tail' variable to just 'node', because tail is not always logically the tail of the list.

The solution is, instead of comparing node->name with node->next->name, you need to compare node->name with the 'insert' node that you are trying to insert. If there is ever a point at which insert's name becomes greater than the current iteration node's name, that's where you need to re-wire the current iteration node's next to point to insert, and insert->next needs to point to what was previously node->next.
Last edited on
Topic archived. No new replies allowed.