简体   繁体   中英

Doubly Linked List logic

I am trying to run a test for a getPrevious() method in JUnit.

public void getPrev(){
    for (int i = 0; i < 1000; i++) {
        list.add(i);    
    }
    list.reset();
    for (int i = 999; i >= 0; i--) {
        int info = list.getPrevious();
        assertEquals(i, info);
    }
}

Every other method seem to work, except for this one. After running some printing tests, I realized that the reset method

...reset(){
    if (list != null)
        location = list.getPrev();//returns the last node's previous node -- head node.
}

(which should make the location node the head node) was not returning the correct information. It returned null instead of the head node.

Thus, my logic led me to believe that the add method was not working as it should be. And this is also my question. I have been trying multiple things to see where the error is but nothing seem to work. I am looking to see if anyone can help spot the logic error in this code.

 public void add(Object elem) {
     LLNode<T> newNode = new LLNode(elem);

     if(list == null){
         tail = list = newNode;
     }
     list.setPrev(newNode);
     newNode.setNext(list);
     newNode.setPrev(tail);
     tail.setNext(newNode);
     list = newNode;
     size++;
 }

Try This

 public int add(Object elem) {
    Node node = new Node(elem);

    if (head == null) {
        head = node;
    } else {
        tail.setNext(node);
        node.setPrevious(tail);
    }

    tail = node;
    return value;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM