链表排序插入

时间:2018-11-11 17:53:14

标签: java sorting data-structures linked-list traversal

我正在尝试插入请求并按优先级对其进行排序,因此,最高(1)在列表中排在首位。

public Node addByPriority(Object request, int priority) {
    size++;
    //creates a new node with a priority, owner and creator and sets its next node to the root
    Node newNode = new Node(request, priority);
    //node to store prev
    Node prevNode = null;
    //node to store current
    Node currNode = first;

    //cycle thru the nodes til either the priority is higher or current is null
    while (currNode != null && priority >= currNode.getPriority()) {
        prevNode = currNode;
        currNode = currNode.getNext();
    }
    if (prevNode == null) {
        newNode.setNext(first);
        first = newNode;
    }
    else {
        prevNode.setNext(newNode);
        newNode.setNext(currNode);
    }
    // what would be the return statement??
}  

它说我需要一个return语句,但是不确定必须输入什么,或者是否还有其他方法。

2 个答案:

答案 0 :(得分:1)

您没有说明应该返回的Node,但是有理由要返回新创建的一个:

return newNode;

答案 1 :(得分:0)

您可以将链接列表的开头返回为:

return first;

这有助于再次访问更新后的列表。