0.5. Link Nodes¶
0.5.1. Link Nodes¶
In this module, we introduce the idea of a link node. This 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. (Need to change this slightly to have better field names: next and element instead of n and e.)
class Link {
public Link next; //Point to next node in list
public Object data; //Value for this node
//Constructors
public Link(Object data, Link next) {
this.data = data;
this.next = next;
}
public Link(Object data) {
this.data = null;
this.next = next;
}
Object getData() {
return data;
} // Return the value
Object setData(Object newData) {
return data = newData;
} // Set element value
Link getNext() {
return next;
} // Return next link
Link setNext(Link newNext) {
return next = newNext;
} // Set next link
}
Here are examples for referencing Link objects in a chain, and getting at the contents of a link object.
How do we set up the chain to begin with?
One can easily write a loop to iterate through all the Links on a chain, without needing to know how many there actually are.
One can remove a Link from a chain.
Finally, we can also insert new Links.
Here is an exercise to practice manipulating link nodes.