尝试将节点添加到链接列表

时间:2017-01-15 14:48:44

标签: java linked-list nodes

我们已经开始使用链接列表和课堂中的节点,我想我理解它们是如何工作的。但是在一个部分,我们必须将节点添加到链表中,我有一些问题要让它工作。 错误发生在方法“append”中。我的IDE并没有告诉我很多关于这个问题的信息。

我的班级LinkedList:

public class LinkedList {
    public Node head = null;

    public void insert(Node n) {
        n.next = head;
        head = n;
    }

    public Node search(int nummer) {
        Node current = head;

        while (current != null) {
            if (current.element == nummer)
                return current;
            current = current.next;
        }
        return null;
    }

    public int count() {
        int c = 0;

        for (Node n = head; n != null; n = n.next) {
            c++;
        }
        return c;
    }

    public void append(Node n) {
        if (head == null){
            head = new Node(n, null);
        }
        else {
            Node p = head;
            while (p.a != null){
                p = (Node) p.a;
            }
        p.a = new Node(n, null);}
    }    
}

我的节点类:

public class Node {
    public int element = 0;
    public Node next = null;
    Object a;

    public Node(int e, Node n) {
    this.element = e;
    this.next = n;
    }

    public Node(int e) {
    this.element = e;
    }

}

1 个答案:

答案 0 :(得分:0)

您正在将字段a视为指向列表中下一个节点的指针。它不是,它实际上是每个列表节点中包含的数据。相反,请修改您的append()方法以使用next

public void append(Node n) {
    if (head == null) {
        head = new Node(n, null);
    }
    else {
        Node p = head;
        // walk down the list from the head until reaching the end
        while (p.next != null) {
            p = (Node) p.next;
        }
        // then append the new Node to the end of the list
        p.next = n;
    }
}

请注意,理想情况下,您应该为Node类设置getter和setter方法。我可能会建议这样的事情:

public class Node {
    private int element = 0;   // no idea what this is for
    private Node next = null;
    private Object a;

    public Node(int e, Node n) {
        this.element = e;
        this.next = n;
    }

    public Node(int e) {
        this.element = e;
    }

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

    public Node getNext() {
        return next;
    }

    public void setA(Object a) {
        this.a = a;
    }

    public Object getA() {
        return a;
    }
}

使用此Node append()方法的更新定义将成为:

public void append(Node n) {
    if (head == null) {
        head = new Node(n, null);
    }
    else {
        Node p = head;
        // walk down the list from the head until reaching the end
        while (p.getNext() != null) {
            p = p.getNext();
        }
        // then append the new Node to the end of the list
        p.setNext(n);
    }
}