简体   繁体   English

插入双链表

[英]Insertion into Doubly linked list

I have a problem with addition of elements in Liked List 我在喜欢列表中添加元素时遇到问题

public class LinkedList {
    public Node first;
    public Node last;

    public LinkedList() {
        first = null;
        last = null;
    }

    public void addFirst(Student student) {
        Node f = first;
        Node newNode = new Node(student);
        first = newNode;
        if (f == null) last = newNode;
        else f.previous = newNode;
    }

    public void addLast(Student student) {
        Node l = last;
        Node newNode = new Node(student);
        last = newNode;
        if (l == null) first = newNode;
        else {
            l.next = newNode;
        }
    }


    public void display() {
        Node current = first;
        while (current != null) {
            //print...
            current = current.next;
        }
    }

My problem is when I run: 我的问题是当我跑步时:

list.addLast(1);
list.addFirst(2);
list.display();

It displays just "2" 'display' method just can't see last added element. 它只显示“ 2”“显示”方法,看不到最后添加的元素。
But if I run: 但是如果我运行:

list.addFirst(2);
list.addLast(1);

It will display both. 它将同时显示。 What is wrong with it? 怎么了 Thanks. 谢谢。

If this list is doubly-linked, shouldn't you be adding a reference in newNode to the elements that come before/after it? 如果此列表是双向链接,您是否不应该在newNode中添加对其之前/之后的元素的引用?

Your display() method traverses node.next but in addFirst() you never set .next - so if you call addFirst() several times, and only that method, what will display() print? 您的显示()方法遍历node.nextaddFirst()你从来没有设置.next -因此,如果调用addFirst()几次,只有这个方法,你会display()打印?

in addFirst you also have to put newNode.next = f , right now you're just updating one side of the bidirectional relationship. 在addFirst中,您还必须放入newNode.next = f ,现在您只是在更新双向关系的一侧。 And since the display uses the next field, it doesn't work as you expect it. 并且由于显示使用下一个字段,因此它无法按预期工作。

Similarly, in addLast you need to add newNode.previous = l , however since the previous field isn't used in the display method, it doesn't appear bugged when you execute it. 同样,在addLast中,您需要添加newNode.previous = l ,但是由于display方法中未使用前一个字段,因此在执行该字段时不会出现错误。

public void addFirst(Student student) {
    Node f = first;
    Node newNode = new Node(student);
    newNode.next = f; // this was missing
    first = newNode;
    if (f == null)
        last = newNode;
    else
        f.previous = newNode;
}

public void addLast(Student student) {
    Node l = last;
    Node newNode = new Node(student);
    newNode.previous = l; // this was missing
    last = newNode;
    if (l == null)
        first = newNode;
    else
        l.next = newNode;
}

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

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