1. Limited time only! Sign up for a free 30min personal tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Homework Help: Problems With Sorting A Linked List In Java

  1. Mar 4, 2014 #1


    User Avatar
    Gold Member

    1. The problem statement, all variables and given/known data

    Create a SortedLinkedList class which implements the LinkedListInterface.

    Remember to use the Comparable class

    Basically, I need to implement a sorted linked list that uses generics and uses compareTo to sort objects. I need it to be able to sort names alphabetically. Can't use priorities or indexes.

    2. Relevant equations

    3. The attempt at a solution

    My main problem is getting the add() function to work properly. It can sort the head and tail, but it's all the stuff in the middle that is the problem. It won't properly sort anything in the middle between the head and tail. It must be something wrong with my while loop.

    Here is my code for the add() function:
    Here is the input:

    and here is the output after running:
    I have honestly been working on this for a week and I don't understand why it's not working. I've followed in class examples for our priority and linked queues and online tutorials that are similar but nothing works. Any help would be appreciated. Thank you.
  2. jcsd
  3. Mar 5, 2014 #2
    I believe the problem is with:
    newNode.next = current.next;
    current.next = newNode;

    It needs to be:
    newNode.next = current;
    lastNode.next = newNode;

    Then you need to keep track of lastNode, which sill always be the one that was before "current".

    So after:
    LinkedListNode<T> current = head;
    you will have a:
    LinkedListNode<T> lastNode = current;

    Then before:
    current = current.next;
    you will have
    lastNode = current;

    Good luck. Let me know how it goes.
  4. Mar 5, 2014 #3


    User Avatar
    Gold Member

    Thank you! My add() function is working perfectly now! To think I labored for a week or more trying to find a solution while the fix was so simple. Thank you again.

    Do you by any chance have any recommendations for texts/tutorials/resources for further understanding of these data structures?
  5. Mar 5, 2014 #4
    As far as recommended texts, I really don't have any recommendations. Different people learn in different ways. I've been coding for over 4 decades and I pick up new material by reading sample code.

    Best of luck!
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook

Have something to add?
Draft saved Draft deleted