Java 链表,在正确的排序位置添加对象

Java 链表,在正确的排序位置添加对象,java,linked-list,Java,Linked List,我正在创建一个链接列表。我已经完成了大部分课程,只是不能理解其中的一些部分 我尝试了不同的代码,但我不知道正确的代码是什么以及如何执行 谁能帮帮我吗 public class LinkedList<T> implements LinkedListADT<T> { private int count; // the current number of elements in the list private LinearNode<T> list

我正在创建一个链接列表。我已经完成了大部分课程,只是不能理解其中的一些部分

我尝试了不同的代码,但我不知道正确的代码是什么以及如何执行

谁能帮帮我吗

public class LinkedList<T> implements LinkedListADT<T> {

    private int count; // the current number of elements in the list
    private LinearNode<T> list; // pointer to the first element
    private LinearNode<T> last; // pointer to the last element

    /*
     * Create an empty list first
     */
    public LinkedList() {
        this.count = 0;
        this.last = null;
        this.list = null;
    }

    // 1. add to end of list
    public void add(T element) {
        LinearNode<T> node = new LinearNode<T>(element);

        if (size() == 0) {
            this.last = node; // This is the last and the
            this.list = node; // first node
            this.count++;
        } // end if
        else if (!(contains(element))) {
            last.setNext(node); // add node to the end of the list
            last = node; // now make this the new last node.
            count++;
        } // end if
    }
}
如何在列表中的正确排序位置添加对象。这就是我所拥有的,但我无法找出正确的代码


导入java.util.*;公共类LinkedListDemo{public static void mainString args[]{//create a LinkedList LinkedList ll=new LinkedList;//将元素添加到链表ll.addF;ll.addB;ll.addD;ll.addE;ll.addC;ll.addLastZ;ll.addFirstA;ll.add1,A2;System.out.println ll://从链表中删除元素的原始内容ll.removeF;ll.remove2;System.out.println de+ll后ll的内容;//删除第一个a+ll后的第一个和最后一个元素ll.removeFirst;ll.removeLast;System.out.println;//获取并设置值对象val=ll.get2;ll.set2,字符串val+Changed;System.out.prin更改后的tlnll:+ll; }}

输出:


ll的原始内容:[A,A2,F,B,D,E,C,Z]删除后的ll内容:[A,A2,D,E,C,Z第一次和最后一次删除后的ll内容:[A2,D,E,C]ll更改后的内容:[A2,D,E,C]

首先遍历列表,直到到达应该输入的位置,然后将该节点及其前面的节点保存到变量中并添加到其中


注意:根据它是第一个节点、最后一个节点还是中间节点,它的添加方式会有所不同,因此请确保您有选择语句来检查它。

我已经看到了这种方式,但这不是我正在做的,也不是我正在做的事情。taverse是什么意思?查看列表,并在每个点进行测试,以查看它是否是要插入的节点通常使用lopp并检查用于对其进行排序的变量是否小于当前节点之后的节点。一旦到达正确位置,它将自动停止循环,只要您一直使用变量保持当前和以前节点的位置,就可以插入t该位置的节点
 /*
 * 2. add in correct sorted position
 */
    public void addSorted(T element) {
    LinearNode<T> node = new LinearNode<T>(element);

    }