我正在尝试对我的DSALinkedList
进行单元测试,但是当我的removeFirst()
方法失败时,它会出现。我无法弄明白为什么。有人可以帮我吗?
或者我在removeFirst()
以外的其他地方出错了?请帮忙!!谢谢你提前!
这是我的DSALinkedList
public class DSALinkedList {
public DSAListNode head;
public DSAListNode tail;
Object[] newValue;
public DSALinkedList(){
head = null;
tail = null;
}
public void insertFirst(Object newValue){
DSAListNode newNd;
newNd = new DSAListNode(newValue);
if (head == null) {
head = newNd;
tail = newNd;
}
else{
newNd.setNext(head);
head = newNd;
}
}
public void insertLast(Object newValue){
DSAListNode newNd;
newNd = new DSAListNode(newValue);
if(head == null){
head = newNd;
}
else {
tail.next = newNd;
tail = newNd;
}
}
public boolean isEmpty() {
return (head == null);
}
public Object peekFirst(){
Object nodeValue;
if (head == null)
throw new IllegalArgumentException("head is empty");
else
nodeValue = head.getValue();
return nodeValue;
}
public Object peekLast(){
Object nodeValue;
if (head == null)
throw new IllegalArgumentException("head is empty");
else
nodeValue = tail.getValue();
return nodeValue;
}
public Object removeFirst(){
Object nodeValue;
if (head == null)
throw new IllegalArgumentException("head is empty");
else
nodeValue = head.getValue();
head = head.getNext();
return nodeValue;
}
}
答案 0 :(得分:0)
首先删除时,有一个边缘情况(当head == tail时)你需要更新头部和尾部。
我怀疑你的单元测试在单次插入后失败,然后从每一端连续移除一次。第二个请求应该抛出一个异常,因为deque现在是空的。
答案 1 :(得分:0)
我发现有两个地方没有处理@Chris提到的需要改进的边缘情况,请参阅评论。
public void insertLast(Object newValue) {
DSAListNode newNd;
newNd = new DSAListNode(newValue);
if (head == null) {
head = newNd;
tail = newNd; // this should be added
} else {
tail.next = newNd;
tail = newNd;
}
}
和此:
public Object removeFirst() {
Object nodeValue;
if (head == null) {
throw new IllegalArgumentException("head is empty");
} else {
nodeValue = head.getValue();
}
head = head.getNext();
// the following block should be added
if (head == null) {
tail = null;
}
return nodeValue;
}