首页 > 解决方案 > 我正在用 Java 构建一个双链表,当我尝试检索任何信息时,似乎下一个和上一个节点始终为空

问题描述

我已经调试了好几个小时,但我看不出我的搜索方法找不到任何东西的任何原因。我的 toString 只返回第一个节点,然后又什么都没有。有人能帮我吗?

在调试时,我可以确认列表的顺序是正确的,我可以在 addLast 和 addFirst 之间切换,并且总是会返回应该是第一个元素,否则,我不知道。第一个总是在 head.info 中出现,在调试过程中我看到了,但是 prev 和 next 仍然为空。提前致谢!

public class DoubleLinkedList {

  private DoubleNode head;

  public DoubleLinkedList() {
    head = null;
  }

  public class DoubleNode {
    int info;
    DoubleNode prev;
    DoubleNode next;

    public DoubleNode(int key) {
      info = key;
      prev = next = null;
    }
  }


  public DoubleNode search(int key) {
    DoubleNode current = this.head;

    while (current != null && current.info != key) {
      current = current.next;
    }
    return current;
  }

  public void addFirst(int key) {
    this.head = new DoubleNode(key);
  }

  public void addLast(int key) {
    DoubleNode node = new DoubleNode(key);
    DoubleNode current;

    if (head == null) {
      this.head = node;
    } else {
      current = this.head;
      while (current.next != null) {
        current = current.next;
        current.next = node;
        node.prev = current;
      }
    }
  }

  public int delete(int key) {
    DoubleNode current, sent;
    current = search( key );
    if (current != null) {
      sent = delete( current );
      return sent.info;
    } else {
      return -1;
    }
  }

  private DoubleNode delete(DoubleNode node) {
    if (node.prev != null) {
      (node.prev).next = node.next;
    } else {
      this.head = node.next;
    }
    if (node.next != null) {
      (node.next).prev = node.prev;
    }
    return node;
  }

  public String toString() {
    String string = "";
    while (head != null) {
      string += head.info + " ";
      head = head.next;
    }
    return string;
  }

  public static void main(String[] args) {
    DoubleLinkedList test = new DoubleLinkedList();
    test.addLast( 3 );
    test.addLast( 5 );
    test.addFirst( 7 );
    System.out.println(test);
    System.out.println( "Search: " + test.search( 1 ) );
  }
}

结果如下:

7,
Search: null

标签: javasearchdoubly-linked-list

解决方案


看看这个例子:

public class Test {
public static void main(String[] args) {
    List list = new List();
    list.addNode("1");
    list.addNode("2");
    list.addNode("3");
    System.out.println(list);// not implemented
}
}

class List {
Node head;
Node tail;

class Node {
    Node next;
    Node previous;
    String info;

    public Node(String info) {
        this.info = info;
    }
}

void addNode(String info) {
    Node node = new Node(info);
    if (head == null) {
        head = tail = node;
    } else if(tail == head){
        Node next = new Node(info);
        tail.next = next;
        head = next;
        head.previous = tail;
    } else{
        Node next = new Node(info);
        Node current = head;
        head.next =next;
        head = next;
        head.previous = current;
    }
}
}

推荐阅读