gpt4 book ai didi

JAVA双链表-单元测试失败

转载 作者:太空宇宙 更新时间:2023-11-04 14:59:04 24 4
gpt4 key购买 nike

我正在尝试对我的 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;
}
}

最佳答案

我发现有两个地方没有处理@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;
}

关于JAVA双链表-单元测试失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22830983/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com