Java 插入到双链接列表中

Java 插入到双链接列表中,java,doubly-linked-list,Java,Doubly Linked List,我正试图以相反的顺序将字符串插入到双链接列表中。但我不确定如何保持插入顺序的相反顺序 这是我下面的代码 theList.insertReverseLexicographicalOrder("B"); theList.insertReverseLexicographicalOrder("A"); theList.insertReverseLexicographicalOrder("H"); theList.insertReverseLexicographicalOrder("D"); theLis

我正试图以相反的顺序将字符串插入到双链接列表中。但我不确定如何保持插入顺序的相反顺序

这是我下面的代码

theList.insertReverseLexicographicalOrder("B");
theList.insertReverseLexicographicalOrder("A");
theList.insertReverseLexicographicalOrder("H");
theList.insertReverseLexicographicalOrder("D");
theList.insertReverseLexicographicalOrder("E");

public void insertReverseLexicographicalOrder(String dd) {
    Link newLink = new Link(dd);
    if (isEmpty()){
        last = newLink;
    }           
        first.previous = newLink;
    }
    newLink.next = first;
    first = newLink;
}

如果您有任何建议,请使用基于我的解决方案的代码。

如何将节点插入链接列表:

  • 如果列表为空,则新节点将成为第一个节点,如果我们跟踪该节点,也将成为最后一个节点
  • 否则,找到要插入的位置,有三种可能,
    a) 新节点必须在第一个节点之前插入
    b) 新节点必须在最后一个节点之后插入
    c) 新节点必须插入到两个现有节点之间
  • 更新适当的引用,可能是
    第一个
    最后一个
    和一些
    下一个
    上一个
    字段,具体取决于插入位置
  • 要查找位置,首先将数据与第一个节点的数据进行比较,以查看是否必须在第一个节点之前插入该数据

    if (newLink.iData.compareTo(first.iData) > 0) {
        // put newLink before first
    } else {
    
    你必须把注意力集中在某个列表节点上。从一开始就遵循列表,直到到达插入点:

        Link focus = first; // focus first node
        while(focus.next != null && newLink.iData.compareTo(focus.next.iData) < 0) {
            focus = focus.next;
        }
        // now you have to insert the new value behind focus, left as exercise
        if (focus.next == null) {
            // newLink becomes the last node in the list
        } else {
           // newLink has to be inserted between focus and focus.next
        }
    }
    
    链接焦点=第一;//焦点第一节点
    while(focus.next!=null&&newLink.iData.compareTo(focus.next.iData)<0){
    focus=focus.next;
    }
    //现在,您必须在焦点后面插入新值,作为练习
    if(focus.next==null){
    //newLink将成为列表中的最后一个节点
    }否则{
    //必须在焦点和焦点之间插入新链接。下一步
    }
    }
    

    然后插入。注意边缘情况,在前端插入和在末端插入略有不同。

    好吧,你假设它已经按相反的顺序,所以你需要某种循环,直到你找到它应该去的地方。。i、 e

    Z、 Y,X,W,L,K,A


    如果你要插入M,那么你应该循环直到你找到L,它在字典上比M大,然后把它插入那里。因为节点有以前的指针,所以插入应该不太难自己理解

    您需要查看列表,比较每个元素。找到要插入的元素之后的元素时停止。我建议您在节点类中实现compareTo方法: 并用它进行比较


    祝你好运

    谢谢你的评论。如果你能发布一些基于我的解决方案的代码,那就太好了。谢谢你的评论。但我无法理解我应该如何继续使用您提供的代码。如果你能根据我的代码发布一些解决方案,那就太好了。谢谢你的帮助。如何前进在帖子里(我已经修正了一个C-ism)。它还不能处理空列表的情况,但这很容易。因为这是家庭作业,我不想给出太多细节。我已经按照你的建议更新了代码,但仍然不起作用。
        Link focus = first; // focus first node
        while(focus.next != null && newLink.iData.compareTo(focus.next.iData) < 0) {
            focus = focus.next;
        }
        // now you have to insert the new value behind focus, left as exercise
        if (focus.next == null) {
            // newLink becomes the last node in the list
        } else {
           // newLink has to be inserted between focus and focus.next
        }
    }