5.6. Link Nodes¶
5.6.1. Link Nodes¶
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.
class Link {
public Link next; //Point to next node in list
public Object data; //Value for this node
//Constructors
public Link(Object dataIn, Link nextIn) {
this.data = dataIn;
this.next = nextIn;
}
public Link(Link nextIn) {
this.data = null;
this.next = nextIn;
}
Object getData() { // Return the data field
return data;
}
void setData(Object newData) { // Set the data field
data = newData;
}
Link getNext() { // Return the next field
return next;
}
void setNext(Link newNext) { // Set the next field
next = newNext;
}
}
Now we'll see some examples for how to use link
nodes to put
chains together.
How do we set up the chain to begin with?
5.6.2. createList¶
One can easily write a loop to iterate through all the Links on a chain, without needing to know how many there actually are.
5.6.3. iterateOverList¶
One can remove a Link from a chain.
5.6.4. changePointeeNext1¶
Finally, we can also insert new Links.
5.6.5. addNodeAtHead¶
Here is an exercise to practice manipulating link nodes.