3

我正在尝试编写一种在恒定时间内添加到单链表末尾的方法。我不知道如何在恒定时间内将指针分配给列表中的最后一个节点。此方法在 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;

}
4

2 回答 2

3

我认为这应该涵盖它:(应该进入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
于 2013-05-17T15:05:09.993 回答
1

您必须实现一个双端队列,允许在列表的头部或尾部插入

如果您的 List 为空,则 head 和 tail 都为空,如果它包含一个元素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;
}
于 2013-05-17T15:02:16.493 回答