You are on page 1of 2

A linked list is just a chain of nodes, with each subsequent node being a child of the

previous one. Many programs rely on linked lists for their storage because these don't have
any evident restrictions. For example, the array list we did earlier could not grow or shrink,
but node based ones can! This means there is no limit (other than the amount of memory)
on the number of elements they can store.

class node
{ private int data; //holds an arbitrary integer
private node next; //reference to the next node

public node(int d, node n) //constructor


{ data = d;
next = n;
}
//these methods let us use our variables
public void setNext(node n)
{ next=n;}

public void setData(int d)


{ data=d;}

public node getNext()


{ return next;}

public int getData()


{ return data;}
}

Now that we have the basic node class that will make up the linked list it’s pretty easy to think up a display
algorithm if we define the first node (and last node) to be:

private static node firstNode; //a reference to the first node


private static node lastNode = null; //a reference to the last node

[Note: by this point we are now in the main class so firstNode and lastNode are class variables]. All you would need
to do is loop while the next node does not equal null. Such that:

public static void display() //displays all the data in the nodes
{ node n=firstNode;
while(n!=null) //loops forward displaying node’s data (the integers)
{ System.out.print(n.getData()+", ");
n=n.getNext(); //move to the next node in the list
}
}
Now we must create the actual linked list by writing a method that will not only construct the node but put it at the end
of the list (set the last node's next pointer to the new node). We already have a reference to the first and last node so
by using that information we can tell one of two conditions: that the node we are creating is the first node or it is not.
So:

public static void create(int d) //inserts the node into the list
{ node n=new node(d,null); //create node
if(lastNode != null) //if it is not the first node
{ lastNode.setNext(n);lastNode=n;}
else //if n is the first node
{ firstNode=n;lastNode=n;}
}

This is basically all you really need to know. All that’s left is just to write a little loop prompting the user for
numbers and then passing those numbers into create() and then to see if it works you can display() the nodes (or
rather the integers) but I’ll leave that up to you.

You might also like