In this module, we introduce the idea of a link node.
A link node has some sort of value field, and a pointer to another link
node.
Later, you will learn about linked lists,
which are made from link nodes.
For now, we will just use them as a simple way to connect some objects
together.
Here is a class definition for a basic link object.
Note that, while the next field references another link
object, the data field is of type Object.
This denotes that we don’t really care what sort of thing one stores
in a link node’s data field.
classLink{publicLinknext;//Point to next node in listpublicObjectdata;//Value for this node//ConstructorspublicLink(ObjectdataIn,LinknextIn){this.data=dataIn;this.next=nextIn;}publicLink(LinknextIn){this.data=null;this.next=nextIn;}ObjectgetData(){// Return the data fieldreturndata;}voidsetData(ObjectnewData){// Set the data fielddata=newData;}LinkgetNext(){// Return the next fieldreturnnext;}voidsetNext(LinknewNext){// Set the next fieldnext=newNext;}}
classLink{publicLinknext;//Point to next node in listpublicObjectdata;//Value for this node//ConstructorspublicLink(ObjectdataIn,LinknextIn){this.data=dataIn;this.next=nextIn;}publicLink(LinknextIn){this.data=null;this.next=nextIn;}ObjectgetData(){// Return the data fieldreturndata;}voidsetData(ObjectnewData){// Set the data fielddata=newData;}LinkgetNext(){// Return the next fieldreturnnext;}voidsetNext(LinknewNext){// Set the next fieldnext=newNext;}}
Now we’ll see some examples for how to use link nodes to put
chains together.
We'll start with the following four Link objects, already connected together, and the first one pointed to by reference variable head. By the way, notice that we use a slash through a Next field to represent null, in the last Link here.