简体   繁体   English

如何将节点插入到具有给定数据的列表中并保持列表在Java中排序

[英]How to insert a node to a list with given data and maintain the list to be sorted in java

How do i add 100 to the linked list while keeping it sorted? 如何在链接列表中添加100并保持排序? I know i have to add an item to the front of a single-linked list and make it point to the first node of the list but am having much trouble in finding ways to start this problem off. 我知道我必须在单链接列表的前面添加一个项目,并使它指向列表的第一个节点,但是在寻找解决此问题的方法时遇到了很多麻烦。

       IntegerNode n3 = new IntegerNode(9, null);
       IntegerNode n2 = new IntegerNode(5, n3);
       IntegerNode head = new IntegerNode(1, n2);

       IntegerNode curr;
       IntegerNode prev;

       //print all the items in the linked-list
       for(curr = head; curr!=null; curr = curr.getNext()) {
           System.out.println(curr.getItem());
       }

       int data = 100;

       //insert an node to the list with the given data, and maintain the list to be sorted
    }
}

The following insert method should be a start: 以下insert方法应作为一个开始:

public void insert(int val){
    if(this.head==null){ //empty
        this.head = new IntegerNode (val);
        this.head.setNext(null);
        return;
    }
    IntegerNode  prev = null;
    IntegerNode  curr = this.head;
    IntegerNode  newNode = new SLLNode(val);
    while(curr!=null && curr.getVal()<val){
        prev = curr;
        curr = curr.getNext();
    }
    if(prev==null){//new element to be placed at first
        newNode.setNext(curr);
        this.head = newNode;
    }
    else if(curr==null){// new element to be placed at end
        newNode.setNext(null);
        prev.setNext(newNode);
    }else{ //intermediate position
        newNode.setNext(curr);
        prev.setNext(newNode);
    }
}

Steps are as follows: 步骤如下:

  1. If the head is null, make a node with the current value and set it as root. 如果head为null,请使用当前值创建一个节点并将其设置为root。
  2. Else iterate through the list to find the largest node with value less than the current node.We keep references to the previous and next nodes of this node. 否则,遍历列表以查找值小于当前节点的最大节点。我们保留对该节点的上一个和下一个节点的引用。
  3. If the prev is null, that menas the value we are inserting is smaller than all values currently in list and should be placed at the first. 如果prev为null,则表示我们要插入的值小于当前列表中的所有值,应放在第一个值上。
  4. If the curr is null, that means we have reached the end of the list iterating and our value is larger than all the nodes currently in list.So we set the node at last. 如果curr为null,则意味着我们已经迭代到列表的末尾,并且我们的值大于列表中当前的所有节点,因此我们最后设置了该节点。

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM