当我将元素添加到我的Deque,然后立即尝试检查它时,它返回null。我已经确保进入的元素不是空的。这里有什么问题:已经尝试检查方法是否正在运行,add 方法在 DLL 和 Deque 中运行。我也尝试过队列尾部并反复进行排队,但它仍然给了我相同的空点例外双链列表类public class DLL<T>{ private static class Node<T>{ T element; Node<T> next; Node<T> prev; public T getElement() { return element; } public void setElement(T element) { this.element = element; } public Node<T> getNext() { return next; } public void setNext(Node<T> next) { this.next = next; } public Node<T> getPrev() { return prev; } public void setPrev(Node<T> prev) { this.prev = prev; } public Node(T ele, Node<T> n, Node<T> p) { element = ele; next = n; prev = p; } } Node<T> header; Node<T> trailer; int size; public DLL() { size = 0; header = new Node<>(null,null,null); trailer = new Node<>(null,null,header); header.setNext(trailer); } public int size() { return size; } public boolean isEmpty() { return size == 0; } public T first() { if(isEmpty()) { return null; } return header.getNext().getElement(); } public T last() { if(isEmpty()) { return null; } return trailer.getPrev().getElement(); } private void addBetween(T ele,Node<T> before, Node<T> after) { Node<T> newN = new Node<T>(ele,after,before); before.setNext(newN); after.setPrev(newN); size++; } public void addFirst(T ele) { addBetween(ele,header.getNext(),header); } public void addLast(T ele) { addBetween(ele,trailer,trailer.getPrev()); } private T remove(Node<T> rem) { Node<T> before = rem.getPrev(); Node<T> after = rem.getNext(); before.setNext(after); after.setPrev(before); size--; return rem.getElement(); }
2 回答
HUWWW
TA贡献1874条经验 获得超12个赞
你错了。它过于复杂,并且具有令人困惑的命名参数。它应该是这样的:addBetween
private void addAfter(T ele, Node<T> after) {
Node<T> newN = new Node<T>(ele, after, after.getNext());
after.getNext().setPrev(newN);
after.setNext(newN);
size++;
}
两者都有并且总是会引入问题,你冒着混淆它们的风险(就像你所做的那样),你不能保证它们是一致的,如果我用不匹配的元素对调用该方法,那会破坏整个列表。afterbefore
然后,您需要通过以下方式调用该方法:
public void addFirst(T ele) {
addAfter(ele, header);
}
public void addLast(T ele) {
addAfter(ele, trailer.getPrev());
}
添加回答
举报
0/150
提交
取消