我正在尝试编写一种方法,该方法将根据每个对象的整数变量(命名优先级)对链接列表的对象进行排序。 我之前使用过冒泡排序和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();
        }
        }
    }
}

===============>>#1 票数:3

您没有初始化temp

 temp.setItem(position);

===============>>#2 票数: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;
        }
    }
}

===============>>#3 票数: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);
}

  ask by user2180462 translate from so

未解决问题?本站智能推荐: