Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.

Java linked list

  • 29-01-2011 06:18PM
    #1
    Registered Users, Registered Users 2 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, Registered Users 2 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, Registered Users 2 Posts: 63 ✭✭Zico-PES


    Thanks duffman


Advertisement