質問

I am trying to unit test my DSALinkedList, but is it coming up as my removeFirst() method failed. I couldn't figure it out why. Could any one please help me with it?

Or did I go wrong anywhere else other than removeFirst() ? PLEASE HELP!! THANK YOU IN advance!

Here is my 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;
}
}
役に立ちましたか?

解決

I found there are two places which didn't deal with the edge cases mentioned by @Chris needed to improve, please see the comment.

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;
    }
}

and this:

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;
}

他のヒント

When you remove first, there is an edge case (when head == tail) that you need to update both head and tail.

I suspect your unit test is failing after a single insert followed by removing once from each end in succession. The second request should throw an exception, as the deque is now empty.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top