我正在尝试编写一种方法,用于在恒定时间内在单个链接列表的末尾添加。我不知道如何在常量时间内为列表中的最后一个节点分配指针。此方法在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;
}
答案 0 :(得分: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
答案 1 :(得分:1)
您必须实现允许在列表的头部或尾部插入的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;
}