1

I am trying to write the remove(T item) and the T remove(int index) functions. The remove(T item) removes the node you input. The T remove(int index) removes the node from the index that you input. I am getting errors every way I try to write the remove function. Any ideas on how to get started?

I tried writing this. Doesn't seem to work when i compile it.

    public boolean remove(T item) { 
        if(first==null)
            System.out.println("The List Is Empty");
        else{
            Node<T> current = first;
            Node<T> previous = current.getPrevious();
            while(current!=null && !current.getData().equals(item)){
                previous=current;
                current=current.getNext();
            }
            if(current == first && current.getData().equals(item)){
                first = first.getNext();
            }else if(current != null)
                previous.setNext(current.getNext());
        }

        size--;
        return true;
    }

Here is the code.

public class LinkedList<T> implements Iterable<T> {
    private int size = 0;
    private Node<T> first = null,
                    last = null;

    class Node<T> {
        private T data;
        private Node<T> next = null;
        private Node<T> previous = null;

        public Node(T item) {
            data = item;
        }

        public T getData() { return data; }
        public void setData(T data) { this.data = data; }
        public Node<T> getNext() { return next; }
        public void setNext(Node<T> next) { this.next = next; }
        public Node<T> getPrevious() { return previous; }
        public void setPrevious(Node<T> previous) { this.previous = previous; }
    }

    public LinkedList() {
        first = new Node<T>(null);  // no data in first
        last = new Node<T>(null);   // no data in last
        first.setNext(last);
        last.setPrevious(first);
    }
    public String toString() {
        StringBuilder build = new StringBuilder("[");
        Node<T> current = first;
        while (current.getNext() != last) {
            current = current.getNext();
            build.append(current.getData());
            if (current.getNext() != last)
                build.append(", ");
        }
        return build.toString() + "]";
    }

    public int size() { return size; }

    // add an item at the end of the list
    public void add(T item) {
        Node<T> newNode = new Node<T>(item);
        Node<T> nextToLast = last.getPrevious();
        nextToLast.setNext(newNode);
        newNode.setPrevious(nextToLast);
        newNode.setNext(last);
        last.setPrevious(newNode);
        size++;
    }

    // add an item at any position other than the end
    // adds such the new item is at position "index" after
    // add is done
    public void add(int index, T item) {
        Node<T> current = first;
        Node<T> newNode = new Node<T>(item);
        for (int i=0; i<= index; i++)
            current = current.getNext();
        Node<T> previous = current.getPrevious();
        previous.setNext(newNode);
        newNode.setPrevious(previous);
        current.setPrevious(newNode);
        newNode.setNext(current);
        size++;
    }

    public T set(int index, T item) {
        if (index >= size) throw new ArrayIndexOutOfBoundsException();
        Node<T> current = first.getNext(); // before it was first;
        for (int i=0; i<index; i++)
            current = current.getNext();
        T answer = current.getData();
        current.setData(item);
        return answer;
    }

    public boolean remove(T item) {     

        return true;
    }

    public T remove(int index) {




        return null;
    }

    public boolean contains(T item) {



        return false;
    }

    public T get(int index) {


        return null;
    }

    // this is the code from the singly linked list implementation,
    // and without empty first and last nodes.
    public Iterator<T> iterator() {
        return new Iterator<T>( ) {
            private Node<T> current = null, previous = null;

            public boolean hasNext() {
                return current != last;
            }

            public T next() {
                previous = current;
                if (current == null) current = first;
                else current = current.getNext();
                return current.getData();
            }

            public void remove() {
                if (current == null)
                    throw new IllegalStateException();
                if (previous == null)
                    first = current.getNext();
                else {
                    previous.setNext(current.getNext());
                    if (current == last)
                        last = previous;
                    current = previous;
                    previous = null;
                }
                size--;
            }
        };
    }

    public static void main(String[] args) {
        Scanner console = new Scanner(System.in);
        LinkedList<Double> theList = new LinkedList<Double>();
        int choice = -1;
        int index;
        do {
            System.out.println("The list is " + theList);
            System.out.println("Enter a choice between 1 and 9");
            System.out.println("1 = add 2 = addindex 3 = set 4 = remove");
            System.out.println("5 = removeindex 6 = contains 7 = get 8 = Iterator");
            System.out.println("9 = Iterator remove");
            choice = console.nextInt();
            switch(choice) {
            case 1:
                System.out.println("Number");
                theList.add(console.nextDouble());
                break;
            case 2:
                System.out.println("Index");
                index = console.nextInt();
                System.out.println("Number");
                theList.add(index, console.nextDouble());
                break;
            case 3:
                System.out.println("Index");
                index = console.nextInt();
                System.out.println("Number");
                theList.set(index, console.nextDouble());
                break;
            case 4:
                System.out.println("Number");
                theList.remove(console.nextDouble());
                break;
            case 5:
                System.out.println("Index");
                index = console.nextInt();
                theList.remove(index);
                break;
            case 6:
                System.out.println("Number");
                System.out.println(theList.contains(console.nextDouble()));
                break;
            case 7:
                System.out.println("Index");
                System.out.println(theList.get(console.nextInt()));
                break;
            case 8:
                System.out.print("Output using Iterator: [");
                for (Iterator<Double> it = theList.iterator(); it.hasNext(); ) {
                      System.out.print(it.next());
                      if (it.hasNext())
                        System.out.print(", ");
                      else
                        System.out.println("]");
                }
                break;
            case 9:
                System.out.println("Index");
                index = console.nextInt();
                Iterator<Double> i = theList.iterator();
                for (int x=0; x<index; x++)
                    i.next();
                i.remove();
                System.out.println(theList);
            default:
                System.out.println("Enter a choice between 1 and 9");
            }
        } while (choice != -1);
    }
}
3
  • What error are you getting? Commented Nov 10, 2014 at 5:16
  • Provide the stack trace of error Commented Nov 10, 2014 at 6:03
  • Exception in thread "main" java.lang.NullPointerException at util.LinkedList.remove(LinkedList.java:91) at util.LinkedList.main(LinkedList.java:189) Commented Nov 10, 2014 at 6:08

1 Answer 1

0

In your constructor you are initializing both first & last node with null data.

public LinkedList() {
    first = new Node<T>(null);  // no data in first
    last = new Node<T>(null);   // no data in last
    first.setNext(last);
    last.setPrevious(first);
}

In your remove(T item) implementation you are checking whether first is null or not (which wont be true because of constructor).

So the code will go into else block and in the first node data is null and hence you will get NPE @ following lines:

  1. while(current!=null && !current.getData().equals(item)){
  2. if(current == first && current.getData().equals(item)){
  3. previous.setNext(current.getNext());

You need to fix your constructor (remove unnecessary initialization of variables) as well as remove method by doing proper data validation.

FYI: You should have test cases for each and every method to catch such issues.

Sign up to request clarification or add additional context in comments.

2 Comments

I cant change anything in the constructor, that was giving to us. I can only change whats in the "public boolean remove(T item)". What i already typed there could be completely wrong. I basically have to reverse the "public void add(T item)" function.
Then you need to do proper data validations in the remove method (like checking node is null or not, if it is not null then check if the data is null or not) and then implement the logic as per the requirement.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.