使用带有链表的冒泡排序

时间:2013-04-16 02:50:21

标签: java sorting linked-list

我正在尝试编写一个方法,该方法将根据每个对象的整数变量(命名优先级)对链表的对象进行排序。我之前在arraylists中使用过冒泡排序并没有遇到任何麻烦,但出于某些原因,当我尝试使用链表时,它会给我一个NullPointerException而我无法弄清楚我做错了什么。有什么建议吗?

public void sortList() {
    boolean flag = true;
    Item temp = null;
    Item position = head;
    Item positionLink = position.link;
    while(flag) {
        flag = false;
        while (position != null) {
            if(position.getPriority() > positionLink.getPriority()) {
                temp.setItem(position);
                position.setItem(positionLink);
                positionLink.link.setItem(temp);
                flag = true;
                position = position.getItem();
        }
        }
    }
}

3 个答案:

答案 0 :(得分:3)

您没有初始化temp

 temp.setItem(position);

答案 1 :(得分:1)

顺便说一句,你的算法看起来不对.. item.link和item.setItem()等有一个混乱......等等..

应该是这样的:

public void sortList() {

    boolean flag = true;
    while (flag) {
        flag = false;

        Item position = head;
        Item positionNext = position.link;
        Item positionPrev = null;

        while (positionNext != null) {
            if(position.getPriority() > positionNext.getPriority()) {

                Item temp = position;
                Item tempNextNext = positionNext.link;
                position = positionNext;
                position.link = temp;
                positionNext = temp;
                positionNext.link = tempNextNext;

                if (positionPrev == null) { // position is head
                    head = position;
                } else {
                    positionPrev.link = position;
                }

                flag = true;
            }
            positionPrev = position;
            position = position.link;
            positionNext = position.link;
        }
    }
}

答案 2 :(得分:0)

 public void bubbleSort() {
        boolean swapped;

        do {
        Node curr = first;
        Node prev = null;
        swapped = false;
        while (curr.next != null) {
            Node fwd = curr.next;

            if (curr.item > curr.next.item) {
                /**
                 * 3 pointers involved: prev, temp and temp.next. simply
                 * follow the order
                 * 
                 * prev.next = temp.next; 
                 * temp.next = temp.next.next;
                 * temp.next.next = temp;
                 */

                /**
                 * egde case: prev: can be null temp & temp.next cannot be
                 * null.
                 */

                if (prev != null) {
                    prev.next = fwd;
                } else {
                    first = fwd;
                }
                // advance prev.
                prev = fwd;

                curr.next = fwd.next;
                fwd.next = curr;
                swapped = true;
            } else {
                prev = curr;
                curr = curr.next;
            }
        }
    } while (swapped);
}