【问题标题】:adding at the end of a singly-linked list in constant time在恒定时间内添加到单链表的末尾
【发布时间】:2013-05-12 19:21:51
【问题描述】:

我正在尝试编写一种在恒定时间内添加到单链表末尾的方法。我不知道如何在恒定时间内将指针分配给列表中的最后一个节点。此方法在 0(n) 中运行:

public void insertEnd(Object obj) {
if (head == null) {
  head = new SListNode(obj);
} else {
  SListNode node = head;
  while (node.next != null) {
    node = node.next;
  }
  node.next = new SListNode(obj);
}
size++;
}

这是我的新方法的开始:

public void addLast(SListNode obj){
  //if the list is empty, the new element is head and tail
  if(tail == null){  
      obj.next = null;
      head = tail = obj;
  }else{   -----> here I'm confused 

  }
}

这是我的 SList 类:

public class SList {
   private SListNode head;
   private SListNode tail;
   private int size;

   public SList() {
   size = 0;
   head = null;
   tail = null;

}

【问题讨论】:

  • 也许将列表末尾存储为类中的字段?
  • 我做到了,但你如何将它实际分配给最后一个元素?
  • @Frugo, tail.next = obj;
  • 我可以在这个线程上获得一些更新吗?

标签: java singly-linked-list


【解决方案1】:

我认为这应该涵盖它:(应该进入else

tail.next = obj; // have (the current tail).next point to the new node
tail = obj; // assign 'tail' to point to the new node
obj.next = null; // may not be required

【讨论】:

    【解决方案2】:

    你必须实现一个Double Ended Queue,它允许在你的列表的头部或尾部插入

    如果你的List为空,则head和tail都为null,如果它包含一个元素head == tail

    public void addLast(SListNode obj){
    //if the list is empty, the new element is head and tail
    if(tail == null){  
      obj.next = null;
      head = tail = obj;
    }else{   -----> here I'm confused 
      tail.next = obj;
      tail = obj;
    }
    

    【讨论】:

      猜你喜欢
      • 2011-07-11
      • 1970-01-01
      • 1970-01-01
      • 2012-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多