Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I need help converting a Singly Linked List to a Sorted Singly Linked List. I th

ID: 3735497 • Letter: I

Question

I need help converting a Singly Linked List to a Sorted Singly Linked List. I think I need to change the insert portion of the code but am not 100% sure how to do so. Any help would be appreciated. Thanks! Here is the code for the Singly Linked List:

public class SinglyLinkedList
{ private Node h;
    public SinglyLinkedList()
    { h = new Node();
        h.l = null;
        h.next = null;
    }
    public boolean insert(Listing newListing)
    { Node n = new Node();

        if(n == null)
           return false;
        else
        { n.next = h.next;
           h.next = n;
           n.l = newListing.deepCopy();
           return true;
         
        }
       
    }
public Listing fetch(String targetKey)
{ Node p = h.next;
     while (p != null && !(p.l.compareTo(targetKey) == 0))
     { p = p.next;
     }
     if(p != null)
        return p.l.deepCopy();
     else
        return null;
}
public boolean delete(String targetKey)
{ Node q = h;
      Node p = h.next;
      while (p != null && !(p.l.compareTo(targetKey) == 0))
      { q = p;
          p = p.next;
      }
      if(p != null)
      {   q.next = p.next;
           return true;
      }
      else
           return false;
}
public boolean update(String targetKey, Listing newListing)
{ if(delete(targetKey) == false)
         return false;
      else if(insert(newListing) == false)
        return false;
      return true;
}
public void showAll()
{ Node p = h.next;
     while (p != null)
     {   System.out.println(p.l.toString( ));
          p = p.next;
     }
   }
public class Node
{ private Listing l;
      private Node next;
      public Node()
     {
     }
   }
}

Explanation / Answer

Your insert function should be like above and there is nothing else that needs to be changed.. Also, Your listing class should implement comparable interface, so that 2 listing object can be compared for sorting.

In case of any doubts, please ask in comments. If the answer helps you, please upvote. Thanks!

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote