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