Package com. test. ds. Permission list;
Public class category list {
Long count;
Node head;
Public writable list (){
Count = 0;
}
Public void add (Object value ){
Node newNode = new Node (value );
If (head = null ){
// If the linked list is empty, direct the header pointer to newNode
Head = newNode;
} Else {
// If the linked list is not empty, add a node after the End Node
GetNodeByIndex (count-1). next = newNode;
}
Count ++;
}
Public Node getNodeByIndex (long index ){
If (index <0 | index> = count ){
Throw new IndexOutOfBoundsException ("exceeds the maximum index of the Linked List ");
}
Node searchNode = head;
// Pay attention to the I range.
// I cannot be greater than or equal to index, because when index = count-1, searchNodex. next must be null.
//, Causing NullPointerException
For (long I = 0; I <index; I ++ ){
SearchNode = searchNode. next;
}
Return searchNode;
}
Public void removeAt (long index ){
If (index <0 | index> = count ){
Throw new IndexOutOfBoundsException ("exceeds the maximum index of the Linked List ");
}
// Delete the header Node
If (0 = index ){
Head = head. next;
} Else {
//// First locate the index precursor Node
Node preNode = getNodeByIndex (index-1 );
PreNode. next = preNode. next. next;
}
Count --;
}
/**
* Add a node to the specified index
*
* @ Param index
* @ Param value
*/
Public void insert (int index, Object value ){
Node tempNode;
If (0 = index ){
If (null = head ){
Head = new Node (value );
} Else {
TempNode = new Node (value );
TempNode. next = head;
// The inserted node becomes the first node.
Head = tempNode;
}
} Else {
// Locate the parent node of the node index
Node preNode = getNodeByIndex (index-1 );
TempNode = new Node (value );
TempNode. next = preNode. next;
PreNode. next = tempNode;
}
Count ++;
}
Private class Node {
Object data;
Node next;
Public Node (Object value ){
This. data = value;
}
}
Public long size (){
Return count;
}
@ Override
Public String toString (){
Node tempNode = head;
StringBuffer sb = new StringBuffer ();
While (tempNode! = Null ){
Sb. append ("\ t" + tempNode. data. toString ());
TempNode = tempNode. next;
}
Return sb. toString ();
}
Public static void main (String [] args ){
Jsonlist list = new jsonlist ();
List. add (1 );
List. add (2 );
List. add (3 );
List. add (4 );
System. out. println ("Add 1, 2, 3, 4 to the empty linked list:" + list. toString ());
List. removeAt (3 );
List. removeAt (2 );
List. removeAt (1 );
System. out. println ("after removing data at 3, 2, 1:" + list. toString ());
List. insert (1, 2 );
List. insert (2, 3 );
List. insert (3, 4 );
System. out. println ("insert data on location 1, 2, 3:" + list. toString ());
}
}