Search code examples
javaarraylistlinked-listnodesgeneric-programming

How to print LinkedList Node object in reverse order


In the following method reverse() ,I wanted to access the elements of Node and add them in an ArrayList.After that ,using loop, it will print in reverse order.

public void reverse(){

            Node e = head;
            ArrayList<E> s = new ArrayList<E>();
            while(e!=null){

                s.add(e.element);
                e= e.next;
            }
            for (int i = count-1; i >= 0; i--) {
                System.out.print (""+s.get(i));
            }
            System.out.println("");

    }

But, s.add(e.element) ; is giving an error. Here is Node class,

public class Node<E> {
    E element;
    Node<E> next;

    public Node(E element){
        this.element=element;
        next =null;
    }
}

and LinkedList class

     public class LinkedListStack<E> implements Stack<E>{
            Node<E> head;
            Node<E> tail;
            int count=-1;

            public LinkedListStack() {
               head=tail=null;
            }

     public void push(E element) {
            Node<E> newNode = new Node<>(element);
            if(count==-1){
                head=tail=newNode;
                count++;
            }
            else{
                newNode.next=head;
                head = newNode;
            }
            count++;
        }
             public void reverse(){

                Node e = head;
                ArrayList<E> s = new ArrayList<E>();
                while(e!=null){

                    s.add(e.element);
                    e= e.next;
                }
                for (int i = count-1; i > 1; i--) {
                    System.out.print (""+s.get(i));
                }
                System.out.println("");

            }
}

I will appreciate if someone explains the the error for adding Object

element in the ArrayList in details.


Solution

  • You're using the generic Node type as a raw type:

    Node e = head;
    

    should be

    Node<E> e = head;