Question

I am trying to create a Linked list.Here's my code.

public class Node{
    private String element;
    private Node next;
    public Node(String element,Node next){
        this.element=element;
        this.next=next;
    }
    public Node(String element){
        this(element,null);
    }
    public void setElement(String newElem){
        element=newElem;
    }
    public void setNext(Node newNext){
        next=newNext;
    }
    public String getElement(){
        return element;
    }
    public Node getNext(){
        return next;
    }
}


public class SLinkedList{
    protected Node head;
    protected long size;
    public SLinkedList(){
        head=null;
        size=0; 
    }
    public void addElem(String e){
        v=new Node(e,head);
        v.setElement(e);
        v.setNext(head);
        head=v;
        size++;
        System.out.println(v.getElement());
    }
    public static void main (String args[]){
        SLinkedList l=new SLinkedList();
        l.addElem("Element");
        //System.out.println(l.getElement());
    }

}  

My question is when I set

 public void addElem(String e){
            v=new Node(e,head);
            v.setElement(e);
            v.setNext(head);
            head=v; 

it gives an error .But if I change addItem as

public void addElem(String e){
        Node v=new Node(e,head);
        head=v;
        size++;
        System.out.println(v.getElement());
    }  

this works fine.Do I need to call always through the constructor?what's the point of having set methods ?
Also is there a way I can print out the element other that having System.out.println(v.getElement());inside addElem()

Was it helpful?

Solution

  1. Your problem is that you are not declaring what v means in the first code, whereas in the second code you are explicitly declaring it.

    v=new Node(e,head);
    

    Since you have not defined v previously, the JVM does not know what v is

    Node v=new Node(e,head);
    

    This tells the JVM that v is of type Node.

  2. The point of having constructors is that you set all variables in one go rather than using multiple setter methods. You can always use individual setter methods provided they are public

  3. The way you have desinged your code, you will always have to call getElement() to print the value.

OTHER TIPS

 public void addElem(String e){
        v=new Node(e,head);
        v.setElement(e);
        v.setNext(head);
        head=v; 

In above code v is undefined .. So how can it compiles.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top