降序链接列表节点插入

时间:2019-04-07 10:49:51

标签: java linked-list iteration

我有以下代码用于插入节点。但是,它以升序插入它们:

public void add(T item, int priority) throws QueueOverflowException {    
    SortedLinkedListNode<T> current = head;
    SortedLinkedListNode<T> previous = new SortedLinkedListNode<T>(); 
    SortedLinkedListNode<T> newNode = new SortedLinkedListNode<T>(); 
    newNode.priority = priority;
    newNode.data = item; 
    previous =null;

    while (current != null && current.priority <= priority) {
        previous = current;
        current = current.next;
    }

    if (previous == null) {
        newNode.next = current;
        first = newNode;
    } else {
        newNode.next = current;
        previous.next = newNode;
    }
}

不过,我需要将其以降序插入,因此,非常感谢您了解如何实现此目的。

1 个答案:

答案 0 :(得分:0)

您需要将<=更改为>=

public void add(T item, int priority) throws QueueOverflowException {    
    SortedLinkedListNode<T> current = head;
    SortedLinkedListNode<T> previous = new SortedLinkedListNode<T>(); 
    SortedLinkedListNode<T> newNode = new SortedLinkedListNode<T>(); 
    newNode.priority = priority;
    newNode.data = item; 
    previous =null;

    while (current != null && current.priority >= priority) {
        previous = current;
        current = current.next;
    }

    if (previous == null) {
        newNode.next = current;
        first = newNode;
    } else {
        newNode.next = current;
        previous.next = newNode;
    }
}