我正在尝试编写一种在常数时间内向单链表末尾添加元素的方法。我不知道如何在常数时间内将指针分配给列表中的最后一个节点。该方法运行时间为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;
}
tail.next = obj;
- BLuFeNiX