public class IntNode
{
private int data; // The element stored in this node
private IntNode link; // Refers to the next node in the list
...
null
.null
.head = new IntNode(newData, head);
head = head.getLink();
Activating the following method adds a new node after the selected node (using element as the new data):
selection.addNodeAfter(element);
The implementation of addNodeAfter needs only one statement to accomplish its work:
link = new IntNode(element, link);
Activating the following method removes the node after the selected node:
selection.removeNodeAfter( );
The implementation of removeNodeAfter needs only one statement to accomplish its work:
link = link.link;
public static int listLength(IntNode head)
{
IntNode cursor;
int answer;
answer = 0;
for (cursor = head; cursor != null; cursor = cursor.link)
answer++;
return answer;
}
public static IntNode listSearch(IntNode head, int target)
{
IntNode cursor;
for (cursor = head; cursor != null; cursor = cursor.link)
if (target == cursor.data)
return cursor;
return null;
}
public static IntNode listPosition(IntNode head, int position)
{
IntNode cursor;
int i;
if (position <= 0)
throw new IllegalArgumentException("position is not positive.");
cursor = head;
for (i = 1; (i < position) && (cursor != null); i++)
cursor = cursor.link;
return cursor;
}
public static IntNode[ ] listCopyWithTail(IntNode source)
{
// Notice that the return value is an array of two IntNode components.
// The [0] component is the head reference for the new list and
// the [1] component is the tail reference for the new list.
// Also notice that the answer array is automatically initialized to contain
// two null values. Arrays with components that are references are always
// initialized this way.
IntNode copyHead;
IntNode copyTail;
IntNode[ ] answer = new IntNode[2];
// Handle the special case of an empty list.
if (source == null)
return answer; // The answer has two null references.
// Make the first node for the newly created list.
copyHead = new IntNode(source.data, null);
copyTail = copyHead;
// Make the rest of the nodes for the newly created list.
while (source.link != null)
{
source = source.link;
copyTail.addNodeAfter(source.data);
copyTail = copyTail.link;
}
// Return the head and tail references for the new list.
answer[0] = copyHead;
answer[1] = copyTail;
return answer;
}
ArrayList)
and based on linked lists (LinkedList
).