I need to modify the insert method of my program so that it inserts items into a singly linked list in ascending order. I understand what a linked list is but have no clue how to insert the items in order. Here are my programs so far(not the entire program):
public class SinglySortedLinkedList
{ private Node h; // list header
public SinglySortedLinkedList()
{ h = new Node(); // dummy node
h.l = null;
h.next = null;
}
public boolean insert(Listing newListing)
{ Node n = new Node();
if(n == null) // out of memory
return false;
else
{
n.next = h.next;
h.next = n;
n.l = newListing.deepCopy();
return true;
}
}
here is the tester method:
public class MainSinglyLinkedList
{ public static void main(String[] args)
{ SinglySortedLinkedList boston = new SinglySortedLinkedList();
Listing l1 = new Listing("Bill", "1st Avenue", "123 4567" );
Listing l2 = new Listing("Al", "2nd Avenue", "456 3232");
Listing l3 = new Listing("Mike", "3rd Avenue", "333 3333");
boston.insert(l1); // test insert
boston.insert(l2);
boston.insert(l3);
boston.showAll();
l3 = boston.fetch("Mike"); // test fetch of Mike
System.out.println(l3.toString());
boston .delete("Al"); // test delete of Al
boston.showAll();
boston.update("Mike", l2); // test update of Mike to Al
boston.showAll();
System.exit(0);
}
}
Any ideas of some pseudocode of how to insert in ascending order by the names would be so great, thanks