First, let's take a look at the principles of the linked list mode:
First, write a JavaBean. The content is the element to be added and the node of the element.
Public class nodebean implements serializable
{
Private object data; // The element itself
Private nodebean next; // The next node
Public object getdata ()
{
Return data;
}
Public void setdata (Object Data)
{
This. Data = data;
}
Public nodebean getnext ()
{
Return next;
}
Public void setnext (nodebean next)
{
This. Next = next;
}
Public nodebean (Object Data, nodebean next)
{
This. Data = data;
This. Next = next;
}
Public nodebean ()
{
}
Public String tostring ()
{
Return data + "" + next;
}
}
Next, write an iterator class. For example, my class name is iteratorlinkedmodel, which has some functional methods. Here we will introduce the method to be added. At the same time, it contains many nodes, including the Start Node and end node.
Public class iteratorlinkedmodel
{
// Start Node
Nodebean head = NULL;
// Counter, which records the number of elements in the current linked list
Int size = 0;
// When we add a new element, if we know which element is the last one,
// You can point the node of the last element to the node of the new element,
// Declare an end node, and the initial value is empty.
Nodebean tail = NULL;
// Add elements to the linked list
Public object add (Object O)
{
// A new node is used to input data. The initial next operation does not exist. Therefore, a null value is passed.
Nodebean NB = new nodebean (O, null );
// Judge whether the head is empty.
If (Head = NULL)
{
// If the head is empty, it indicates the first node,
// Point the head reference to the newly constructed Node object.
Head = Nb;
// If the head is Nb, the tail is Nb,
// That is to say, the first node is the leader and the Dragon Tail
Tail = Nb;
}
Else
{
// In other cases, if the head is not equal to null, that is, it is not the first node.
// Point the last node to the newly added Node
Tail. setnext (NB );
// At the same time, tail itself should be the newly added node.
Tail = Nb;
}
// As long as a new node is added in, the counter begins to accumulate
Size ++;
Return O;
}
// Return the Count result
Public int size ()
{
Return size;
}
}
Finally, write a test class and give it a try.
Public class test
{
Static object O;
Public static void main (string [] ARGs)
{
Iteratorlinkedmodel ILM = new iteratorlinkedmodel ();
For (INT I = 1; I <5; I ++)
{
O = ILM. Add (I );
System. Out. println (O );
}
System. Out. println ("counter Result:" + ILM. Size ());
}
}
Finally, the content in the output object is: 1, 2, 3, 4, and the counter result is 4 OK! Successful!