Public class MyList { StaticClass Node {//Node classObject data; Node Next; Public Node(Object data) {//Construct method, assign value to data This. data = data; This. Next =NULL; }} Node head; Public MyList() {head =NULL;//Chain list construction method} Public void Clear() {//Clear linked listHead =NULL; } Public void Bianli()//traversal {Node p = head; while(P! =NULL) {System.out.print (P.data +" "); p = p.next; } System.out.println (); } Public Boolean IsEmpty()//determine if NULL {returnHead = =NULL; } Public int size() {//Number of nodesNode p = head;intsum =0; while(P! =NULL) {sum++; p = p.next; }returnSum }//Insert element at specified position, subscript starting from 0 Public void Insert(Object D,intPOS) {if(Pos <0|| pos > Size ()) {Throw NewRuntimeException ("Subscript Error"); } Node NewNode =NewNode (d);if(pos = =0) {newnode.next = head; head = NewNode; }Else if(Pos >= size ()-1) {Get (Size ()-1). Next = NewNode; }Else{Newnode.next = Get (POS); Get (POS-1). Next = NewNode; } } PublicNodeGet(intPOS) {if(Pos <0|| pos > Size ()) {Throw NewRuntimeException ("Subscript Error"); }if(pos = =0)returnHead Node p = head; for(inti =0; I < POS; i++) p = p.next;returnP } Public Static void Main(string[] args) {MyList list =NewMyList (); List.insert (Ten,0); List.insert ( -,1); List.insert ( -,0); List.insert ( +,1); System.out.println (List.size ()); List.bianli (); System.out.println (List.isEmpty ()); System.out.println (List.get (2). data); List.clear (); System.out.println (List.isEmpty ()); }}
Java implementation of a linked list