Java - Ordered Linked List算法

时间:2017-08-22 06:13:18

标签: java algorithm list sorting

我在理解链接列表的算法时遇到问题,如果有人可以为我解释,当新添加的项目少于上一项时,我几乎理解了所有内容,所以我们必须移动新项目项目左侧

public boolean addItem(ListItem newItem) {
    if (this.root == null) {
        // The list was empty, so this item becomes the head of the list
        this.root = newItem;
        return true;
    }

    ListItem currentItem = this.root;
    while (currentItem != null) {
        int comparison = (currentItem.compareTo(newItem));
        if (comparison < 0) {
            // newItem is greater, move right if possible
            if (currentItem.next() != null) {
                currentItem = currentItem.next();
            } else {
                // there is no next, so insert at end of list
                currentItem.setNext(newItem).setPrevious(currentItem);
                return true;
            }
        } else if (comparison > 0) { 
            // newItem is less, insert before
            if (currentItem.previous() != null) {
                currentItem.previous().setNext(newItem);//previous entry is now the added item
                newItem.setPrevious(currentItem.previous()); //the new item previous entry is setted to the current item previous value
                newItem.setNext(currentItem); //pointing the new item to the current item
                currentItem.setPrevious(newItem); //the previous entry of the current item is equal with the new item

            } else {
                // the node with a previous is the root
                newItem.setNext(this.root).setPrevious(newItem);
                this.root = newItem;
            }
            return true;
        } else {
            // equal
            System.out.println(newItem.getValue() + " is already present, not added.");
            return false;
        }
    }

    return false;
}

因此,当比较大于0时,让我说我有:9 11 10在我的链接列表中,所以前一个10,即11到达前一个位置,newItem(10)被设置使用currentItem.previous值到上一个位置,那么当前项目现在也不是10?

2 个答案:

答案 0 :(得分:2)

算法很简单。为了更清楚,让我用一个简单的英文解释替换代码块:

if the list is empty, put the new item as the root of the list.
otherwise, if the list has items, take the root as the current item to compare it to. 
this will go over a few iterations until we find the right spot to insert the new item. 

For every iteration:

  if the new item is bigger than the current spot on the list, move up one spot in the 
  list to compare next time.

  else, if the new item is smaller than the current spot, 
  and the current spot is not the root of the list - insert 
  the new item between the current spot and the one before it.

  If the current spot is the root of the list, make the new item 
  the root of the list and tag along the entire list as its next items.

就是这样 - 经过几次迭代后,你总能获得一个排序列表(大多数迭代是列表的长度)。从列表的开头开始,根据您必须插入的项目查看每个项目。如果它比当前点大,那么你就会向上移动。当你通过它需要的位置(前一个点较小,下一个点更大)你只需将它插入中间。您可以在开头或最后插入它。我希望这有助于您更好地理解算法。

答案 1 :(得分:0)

这是

的实施
  • 已排序的链接列表
  • 链接列表
  • 中不允许重复
  • 所有元素都是唯一且按升序排列。