0

I have this singly linked list where each node holds a name and a weight. I'm trying to write a method that will spit out the list by weight(least to greatest).

Here is the method of the SLL class:

public void printWeights() {
            int weightCache;
            String nameCache;
            index=this.head;
            for (int j = 0; j < count; j++) {                    
                for (int i =0; i<count-j;i++) {
                    indexCheck = index.next;
                    if (index.next==null||indexCheck==null){                          
                        index=index.next;
                        indexCheck = index.next;
                         break;
                    }
                        if (index.weight>indexCheck.weight) {
                            weightCache = index.weight; nameCache = index.name;
                            index.weight=indexCheck.weight; index.name=indexCheck.name;
                            indexCheck.weight= index.weight; indexCheck.name= index.name;
                            indexCheck.weight = weightCache;indexCheck.name = nameCache;  
                            indexCheck=indexCheck.next;
                        }
            }


            }
            if (head == null) {
                System.out.println("List is Empty!");
            }
            for (int i = 1; i <= count; i++) {
                if (i < count) {
                    System.out.print(this.head.name + " - " + this.head.weight + ", ");
                    head = head.next;
                } else {
                    System.out.print(this.head.name + " - " + this.head.weight + ". \nDone.");
                }

            }

        }
Lunch
  • 57
  • 1
  • 1
  • 7
  • What sorting algorithm are you implementing? Can you describe its logic? – PM 77-1 Nov 17 '13 at 04:31
  • What you appear to be trying to do is to iterate through the list N times, with each iteration picking out the next highest value. An N-squared algorithm, if it even works. And you're not actually sorting the linked list. – Hot Licks Nov 17 '13 at 04:35
  • Look at this similar question: http://stackoverflow.com/questions/842407/how-can-i-sort-a-singly-linked-list-in-constant-space – Dave Nov 17 '13 at 05:45
  • The list is sorted while the user inputs it in alphabetical order. Then this method prints it out in weight order. – Lunch Nov 17 '13 at 18:17
  • I just tried some new logic that got me closer. but the order is still messed up. Tried using a bubble sort type logic. – Lunch Nov 17 '13 at 19:09

0 Answers0