문제

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.
But if I run:

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

It will display both. What is wrong with it? Thanks.

도움이 되었습니까?

해결책

in addFirst you also have to put newNode.next = f, right now you're just updating one side of the bidirectional relationship. 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.

다른 팁

If this list is doubly-linked, shouldn't you be adding a reference in newNode to the elements that come before/after it?

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?

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 ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top