在java中的链接列表的末尾添加元素

时间:2016-12-11 12:08:11

标签: java linked-list add

我们开始在学校学习列表,但我真的不明白它们是如何工作的。作为家庭作业,我们必须编写一个方法添加,在列表的末尾添加一个元素。我不知道为什么,但是当我添加更多节点时,列表只保存前两个节点。我想知道为什么以及我应该改变什么。这是代码(我不允许更改给定代码中的任何内容。我只能创建新方法...)

public class HeadList {

    Entry head;

    public HeadList() {
        head = null;
    }

    /**
     * Appends a new element with value info to the end of this list
     * @param info value of the new element
     */
    public void add(int info) {
        //TODO

       Entry node = head;

        if (head != null) {
            if (node.next == null){
                node.next = new Entry(node, null, info);
            }
            else{
                Entry n = node.next;
                while(n != null){
                    n = n.next;
                }
                node = new Entry(node, null, info);
            }
        }
        else
            head = new Entry(null, null, info);

    }
    @Override
    public String toString() {
        String out = "[";
        if (head != null) {
            out += head.elem;
            Entry tmp = head.next;
            while (tmp != null) {
                out = out + "," + tmp.elem;
                tmp = tmp.next;
            }
        }
        out += "]";
        return out;
    }

    public static void main(String[] args) {
        HeadList l = new HeadList();
        l.add(6);
        l.add(7);
        l.add(8);
        l.add(9);
        System.out.println("empty list: " + l);
        // Test implementation

    }

    class Entry {

        Entry first;
        Entry next;
        int elem;

        public Entry(Entry first, Entry next, int elem) {
            this.first = first;
            this.next = next;
            this.elem = elem;
        }

    }

}

1 个答案:

答案 0 :(得分:0)

将您的添加方法更改为:

public void add(int info) {

    Entry node = head;

    if (head != null) {
        if (node.next == null){
            node.next = new Entry(node, null, info);
        }
        else{
            Entry n = node.next;
            while(n != null){
                node =n;
                n = n.next;
            }
            Entry next = new Entry(node, null, info);
            node.setNext(next);

        }
    }
    else
        head = new Entry(null, null, info);

}

还会更新您的Entry类:

    class Entry {

    Entry first;
    Entry next;
    int elem;

    public Entry(Entry first, Entry next, int elem) {
        this.first = first;
        this.next = next;
        this.elem = elem;
    }

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

   }