简体   繁体   English

双链表逻辑

[英]Doubly Linked List logic

I am trying to run a test for a getPrevious() method in JUnit. 我正在尝试在JUnit中运行getPrevious()方法的测试。

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. 它返回null而不是head节点。

Thus, my logic led me to believe that the add method was not working as it should be. 因此,我的逻辑让我相信add方法不能正常工作。 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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