Home > database >  Problems inserting element at the tail of a list JAVA
Problems inserting element at the tail of a list JAVA

Time:01-22

My assignment is implementing a linkedList as a queue. I'm having a problem adding elements at the tail of the list. I get no Exception but the problem is that when adding a element, the list still is empty afterwards and I really don't see the problem. Someone who has a solution? :)

@Override
public void add(E element) {
        if(element == null){
            throw new NullPointerException();
        }else{
            this.addNodeLastInQueue(element); 
        }
    
}


public void addNodeLastInQueue(E element){
    
        MyNode<E> nodeToBeAdded = new MyNode<E>(element);  
        if(isEmpty()){
            head = nodeToBeAdded;
            tail = nodeToBeAdded;//Osäker om denna behövs
        }else{
            tail.setNext(nodeToBeAdded);   
            tail = nodeToBeAdded;
        }  
    }

I have tried with everything I an come up with

CodePudding user response:

public class MyNode<E> {

        private E data;
        private MyNode <E> next;
  
        public MyNode(E data) {
           this.data = data;
           this.next = null; 
        }  
    }

public void enQueue(E element) {
        MyNode<E> oldTail = tail;
        tail = new MyNode<E>(element);
        tail.data = element; 
        tail.next = null;
        if (isEmpty()) head = tail;
        else           oldTail.next = tail;
    }


@Override
public void add(E element) {
    if(element == null){
        throw new NullPointerException();
    }else{
        this.enQueue(element); 
    }
    
}

CodePudding user response:

By definition when you add an element in a queue this goes automatically at the end of the list (see FIFO), so you don't need to call the method "addNodeLastInQueue". The best practice is to call it "enqueue".

Here the method:

public void enqueue(E element) {
    Node<E> oldlast = last;
    last = new Node<E>();
    last.e = e; // It refers to the "e" attribute in static class
    last.next = null;
    if (isEmpty()) first = last;
    else           oldlast.next = last;
    n  ;
}

Hint: I suggest you to implement a helper linked list static class in order to provide Node attributes to the queue. In fact i use it in my method.

// helper linked list class
private static class Node<E> {
    private E e;
    private Node<E> next;
}

I hope I have been of help. Bye!

  • Related