【问题标题】:Insert into Doubly LinkedList插入双向链表
【发布时间】:2012-02-18 02:08:46
【问题描述】:

我想以相反的顺序将字符串插入双向链表。但我不确定如何以相反的顺序维护插入顺序。

这是我下面的代码。

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;
}

任何建议都将根据我的解决方案使用一些代码表示赞赏..

【问题讨论】:

    标签: java doubly-linked-list


    【解决方案1】:

    你假设它已经是相反的顺序,所以你需要某种循环,直到你找到它应该去的地方......即

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

    如果你要插入 M,那么你应该循环直到找到 L,它在字典上比 M 大,因此将它插入那里。因为节点有先前的指针,插入不应该太难自己弄清楚

    【讨论】:

    • 感谢您的评论。如果您可以根据我的解决方案发布一些代码,那将是非常好的理解。
    【解决方案2】:

    您需要查看比较每个元素的列表。当您找到要插入的元素之后的元素时停止。我建议你在你的节点类中实现 compareTo 方法:http://www.javapractices.com/topic/TopicAction.do?Id=10 并用它来进行比较

    祝你好运。

    【讨论】:

      【解决方案3】:

      如何将节点插入到链表中:

      1. 如果列表为空,新节点将成为第一个,如果我们跟踪它,也是最后一个
      2. 否则找到插入的位置,有三种可能,
        a) 必须在第一个节点之前插入新节点
        b) 必须在最后一个节点之后插入新节点
        c) 新节点必须插入两个现有节点之间
      3. 更新适当的引用,可能是 firstlast 和一些 nextprevious 字段,具体取决于必须插入的位置
      if (first == null) {
          // the list is empty so far
      } else
      

      要找到位置,首先将数据与第一个节点的数据进行比较,看看是否必须在第一个节点之前插入。

      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
          }
      }
      

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

      【讨论】:

      • 感谢您的评论。但我无法理解我应该如何继续使用您提供的代码。如果您可以根据我的代码发布一些解决方案,那就太好了。感谢您的帮助。
      • 如何前进在帖子中(我现在已经修复了一个 C-ism)。它还没有处理空列表的情况,但这很容易。既然是作业,我不想透露太多细节。
      • 我已根据您的建议更新了代码,但仍然无法正常工作。
      猜你喜欢
      • 1970-01-01
      • 2018-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-29
      • 2011-07-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多