I am learning how to work with classes. I have made two classes and one is a list of cars. However, I need to modify the add function so that it will add cars sorted by price. The problem I am having is that it will send the cheapest car to the beginning but kill the rest of the list. Here is my code for the add…
public void add_car(the_cars new_car)
{// Method to add cars to list
if (count == 0)
{// If this is the first car
first = new_car;
last = new_car;
count = 1;
}
else
{// If it is not the first car
if (new_car.getPrice() < first.getPrice())
{// If price of new car is lower than first car
last = first;
first = new_car; // new car becomes first car
}
else
{
while (new_car.getPrice() > last.getPrice() || last.next != null)
{
last.next = new_car; // Null value now equal to car
last = new_car;
}
}
count++;
You have identified the cases correctly:
You implemented the first case alright.
The second case is wrong: Inserting in the beginning means to change the first element to
new_car, butnew_car.Nextneeds to point to the previous first element, otherwise you lose the link.The third case is also wrong: You need go towards the end of the list until either you’ve reached the last element (which is then the one you need to insert after) or until you find an element the successor of which has a greater price and insert after that.
The reason why I can put the
whilecondition like that is that ifcurrent != lastI can be sure that there’s acurrent.Next, otherwise it would belastby definition. The reason I need a temporary iteration element is that if I modifyfirstI lose the entry point to the list.If have not tested the following code, but it should give you a clue and if it doesn’t work, single-step debugging will help you.