SLL按int排序

时间:2013-11-17 04:24:54

标签: java sorting singly-linked-list

我有这个单链表,每个节点都有一个名字和一个重量。我试图写一个按重量吐出列表的方法(最少到最大)。

以下是SLL类的方法:

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.");
                }

            }

        }

0 个答案:

没有答案