Search code examples
javadata-structures

How to insert a new node(as prelast) on the list (Linked List)


Hello I have done the interface (and each one method)

  public   interface List
    {
        public boolean isEmpty();
    
        public int size();
    
        public void insertFirst(Object data);
    
        public void insertLast(Object data);
    
        public Object removeFirst() throws ListEmptyException;
    
        public Object removeLast() throws ListEmptyException;
    }

I have a class with name List and the constructor of it and with all those methods. I want to create one method with name insertprelast (using all methods I have done from the interface) so that it will insert a new node as prelast on the list.In case it can not be insert will throw an exception.

What I did was this : 1. I create a new class ListTooSmallException

public class ListTooSmallException extends Exception {
        public ListTooSmallException(String message) {
            super(message);
        }
    }

2. I add on the class List the method but I don't know how can I do so that I will have the prelast

public void insertprelast(Object obj) throws ListTooSmallException {
    
      

    if (obj == null) {
        throw new ListTooSmallException(" wrong");
    } else {
       // i dont know how to do it  
    }
}

Solution

  • The idea is that you remove the last item from the list, and keep a reference to it, and then insert the given argument at the end, to finally add the saved node back to the end.

    Something like this:

    public void insertPreLast(Object obj) throws ListTooSmallException {
        if (isEmpty()) {
            throw ListTooSmallException("List cannot be empty when calling insertPreLast");
        }
        Object saved = removeLast();
        insertLast(obj);
        insertLast(saved);
    }