Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Java linked list

Options
  • 29-01-2011 6:18pm
    #1
    Registered Users Posts: 63 ✭✭


    Hi

    I have a decent understanding of how linked lists work on paper but I cant get my head around how the nodes are linked in this example. Full code attached. I have spent hours trying to understand this. I'd be grateful if anyone could explain to me.

    class NodeList
    {
    private Node head;

    public NodeList() { head = null; }

    public void insert(String s)
    {
    Node temp = new Node(s);
    temp.next = head;
    head = temp;
    }


Comments

  • Registered Users Posts: 339 ✭✭duffman85


     
    class NodeList
    {
    private Node head;
     
    public NodeList() { head = null; } 
     
    public void insert(String s)
    { 
    Node temp = new Node(s); 
    temp.next = head; 
    head = temp; 
    }
    

    when you insert a node into the list you create a node temp and pass the reference to the head node as the next node of temp.
    then you set the head node to be the temp node

    so the next property(temp.next) of a node stores a reference to (memory location of) the next node in the list
    when you get to the last node in the list the next property is set to null as there is no next node.

    to go from the head of the list to the end node you look at each node's next property and go to the memory location specified if it is not null.


  • Registered Users Posts: 63 ✭✭Zico-PES


    Thanks duffman


Advertisement