For a single-linked list, it requires the most basic data nodes and some important methods.
Methods should be used to search, locate, output, get the list length, sorting, linked list read, linked list output. Here's a single-link list I wrote in Java.
Public classList { Public classnode{//Defining Nodes Public intdata; PublicNode Next; PublicNode (intdata) { This. data =data; } } PrivateNode Head;//head Node PublicNode GetHead () {returnHead; } Public intGetLength ()//get the linked list length{node node=Head; intK = 0; while(Node! =NULL) {k++; Node=Node.next; } returnK; } PublicNode Locate (intIndex) {//Locate the node at index position if(Index <= 0)return NULL; Node Node=Head; intK = 1; while(Node! =NULL&& K <index) {k++; Node=Node.next; } returnnode; } Public voidInputintN) {//Linked list Input if(n <= 0)return; Scanner Reader=NewScanner (system.in); intValue =Reader.nextint (); Head=NewNode (value); Node Node=Head; intK = 1; while(K <N) {k++; Value=Reader.nextint (); Node.next=NewNode (value); Node=Node.next; } } Public voidPrint () {//Linked list OutputNode node =Head; while(Node! =NULL) {System.out.print (Node.data+ " "); Node=Node.next; } } Public voidInsertintIndex, node node) {//Linked list Insertion if(Index <= 0 | | index > getlength ())return; Node cur=Locate (index); Node.next=Cur.next; Cur.next=node; } Public voidDeleteintIndex) {//Delete a node if(Index <= 0 | | index > getlength ())return; Node Node= Locate (index-1); Node del=Node.next; Node.next=Del.next; } Public voidSetData (intIndexintData) {//Modifying node Data if(Index <= 0 | | index > getlength ())return; Node Node=Locate (index); Node.data=data; } Public intGetData (intIndex) {//Get Node Data if(Index <= 0 | | index > getlength ())return-1; Node Node=Locate (index); returnNode.data; } Public voidSort () {//sort linked lists with bubbling sortNode cur =Head; Node tmp=NULL; while(cur! =tmp) { while(Cur.next! =tmp) { if(Cur.data >cur.next.data) { inttemp =Cur.data; Cur.data=Cur.next.data; Cur.next.data=temp; } cur=Cur.next; } tmp=cur; Cur=Head; } }}
The test code is as follows:
Public Static voidMain (string[] args) {List L=NewList (); System.out.println ("Please enter data from the linked list"); L.input (6); System.out.println ("The length of the linked list is:" +l.getlength ()); System.out.println ("The sorted list is"); L.sort (); L.print (); L.setdata (4, 1000); System.out.println ("Modify the 4th data to 1000 and modify it as follows"); L.print (); System.out.println ("The 3rd data in a list is:" + l.getdata (3)); L.delete (2); System.out.println ("After deleting the 2nd data in the linked list, the results are as follows"); L.print (); }
The results of the operation are as follows:
Implementing a single-linked list in Java