| |
Methods for Manipulating Nodes | page 4 of 9 |
Methods for the ListNode* class will consist of those for creating, accessing, and modifying nodes
The constructor for the ListNode class is responsible for creating a node and initializing the two instance variables of a new node. The node's constructor has two arguments, which are the initial values for the node's data and link variables. The constructor's implementation copies its two parameters to the instance variables, value and next :
public ListNode(Object initValue, ListNode initNext)
// post: constructs a new element with object initValue,
// followed by next element
{
value = initValue;
next = initNext;
}
As an example, the constructor can be used by a program to create the first node of a linked list.
ListNode first;
first = new ListNode(new Integer(23), null);
After execution of the two statements, first refers to the header node of a small linked list that contains just one node with the Integer 23.

Since primitive data types (int , double , boolean , etc.), are not objects, it is necessary to convert them to objects using the appropriate wrapper class (Integer for int , Double for double , etc.) to construct a list.
Getting and setting the data and link of the node is accomplished with an accessor method and a modification method for each of its instance variables as follows:
public Object getValue()
// post: returns value associated with this element
{
return value;
}
public ListNode getNext()
// post: returns reference to next value in list
{
return next;
}
public void setValue(Object theNewValue)
{
value = theNewValue;
}
public void setNext(ListNode theNewNext)
// post: sets reference to new next value
{
next = theNewNext;
}
The following short program using ListNode will illustrate the syntax of accessing the data members of a ListNode .
public static void main(String[] args)
{
ListNode list;
list = new ListNode(new Integer(13), null);
System.out.println("The node contains: " +
(Integer)list.getValue());
list.setValue(new Integer(17));
System.out.println("The node contains: " +
(Integer)list.getValue());
}
Run Output:
The node contains: 13
The node contains: 17
*Adapted from the College Board's AP Computer Science AB: Implementation Classes and Interfaces.
|