Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Single Linked List

843785Mar 3 2009 — edited Mar 3 2009
Hi Guys,

I am trying to create a single linked list with one node pointing to the other. Then I have to create a method that displays the contents of the nodes. This method must take the head of the linked list as a parameter.

I have created a class called node to store the data of each node created: This is the class;
public class Node {
    String data;
    Node next;
    
    public Node(String data) {
        setData(data);
        setNext(null);
    } // Constructor
    
    public void setData(String data) {
        this.data = data; 
    }

    public void setNext(Node next) { 
        this.next = next; 
    }

    public String getData() { 
        return data; 
    }
    
    public Node getNext() { 
        return next; 
    }
    
    public String toString() {
        if(data == null)
            return "Node: null";
            else
            return "Node: " + data.toString();
    }
}
The second class is LinkedList which initialises each node and creates the linked list.
public class LinkedList {
    private Node head;

    public LinkedList() {
        setHead(null);
    } // constructor

    private void setHead(Node head) {
        this.head = head;
    } // setHead
    
    private Node getHead() {
         return head;
    } // getHead

    public void add(String data) {
        if(getHead() == null){
            Node temp = new Node(data);
            temp.setNext(getHead());
            setHead(temp);
        }
        else
        {
            add(getHead(), data);
        }
    } // add
    
    public static void main (String args[]){
        Node n1 = new Node();
        n1.setData("Jane");
        if (getHead() == null){
            setHead(n1);
        }else{
        System.out.println ("No initialisation of Linked List");
        n1.setNext(n2);
        Node n2 = new Node();
        n2.setNext(n3);
        n2.setData("Maria");
        Node n3 = new Node();
        n3.setNext(n4);
        n3.setData("Paul");
        Node n4 = new Node();
        n4.setData("Charlene");
}
Am I on the right track? And how can I create the method to display all the nodes which takes the head of the list as a parameter only?

Thanks a lot
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Mar 31 2009
Added on Mar 3 2009
15 comments
882 views