【问题标题】:Understanding doubly linked circular list了解双向循环列表
【发布时间】:2016-04-26 12:41:49
【问题描述】:

我在 CS 课上有一个关于循环双向链表的作业。我们得到一个 Node 类来设置链接等。

public class Node {
private Node previous, next;
private Object data;

public Node(Object data) {
    this.data = data;
}

public Node() {

}

public Node(Object data, Node previous, Node next) {
    this.previous = previous;
    this.next = next;
    this.data = data;
}

public Node getPrevious() {
    return previous;
}

public void setPrevious(Node previous) {
    this.previous = previous;
}

public Node getNext() {
    return next;
}

public void setNext(Node next) {
    this.next = next;
}

public Object getData() {
    return data;
}

public void setData(Object data) {
    this.data = data;
}

}

我们的任务是实现一些方法。在列表类中,创建了一个名为“base”的节点

public class DList {



private Node base;

public DList() {

}

所有方法都需要某种形式的遍历列表。据我了解,将临时节点设置为等于 base.getNext() 将为我提供列表的第一个节点并测试 temp != base 将是我检查是否到达列表末尾,因为基本节点服务作为其余节点的锚(如果我的理解是正确的)。

但是,当我尝试执行以下代码时:

 public int size() {
    int count = 0;
    if (base.getNext() == base)
        return count;
    else {
        Node temp = base.getNext();
        while (temp != base) {
            temp = temp.getNext();
            count++;
        }
    }
    return count;
}

在我说 Node temp = base.getNext(); 的那一行出现空指针异常。对于我的生活,我无法理解为什么,因为就像我之前所说的,我认为 base.getNext() 将是我列表的第一个元素。

【问题讨论】:

  • 不需要虚拟基础节点。在这种情况下,base 最初为空。所以if base == null ...
  • 嗯,基地没有下一个。它什么都没有!我建议你在你的 Node 中添加一个方法“hasNext”,它会让你接下来的任务更容易。

标签: java list linked-list circular-list


【解决方案1】:

不需要虚拟基节点。在这种情况下,base 最初为空。 在这种情况下:

public int size() {
    int count = 0;
    if (base != null) {
        Node temp = base;
        do {
            temp = temp.getNext();
            count++;
        } while (temp != base);
    }
    return count;
}

【讨论】:

    猜你喜欢
    • 2022-01-12
    • 2013-01-05
    • 1970-01-01
    • 2021-07-05
    • 1970-01-01
    • 2021-08-22
    • 2013-11-15
    • 2020-07-14
    相关资源
    最近更新 更多