Using Java to implement a linked list, first define the data structure of the linked list, that is, define a class, LinkedListNode. This defines the node of the list, the node of the linked list is divided into two parts, the data info and links link.
public class LinkedListNode {
public int info;
Public LinkedListNode link;//Here is the link, which points to the memory address of the next node
}
Link started not understand, how link is linklistnode type? Does link not refer to the memory address of a node down? Yes, the memory address of the node is stored here LinkedListNode. Whenever new has a linkedlistnode instance, it allocates memory space in memory and it has a memory address. Link is used to store this memory address. So link is the LinkedListNode type.
How to build a linked list? There is forward build and reverse build.
Forward Build:
Create a linked list with three references, first, point to node one, last, point to final node, NewNode point to new node.
Package com.datastructrue.linkedTable;
public class Buildlistforward {
LinkedListNode First,last,newnode;
int num;
Public LinkedListNode buildList (int[] input) {
if (input.length>0) {
for (int i=0;i<input.length;i++) {
Newnode= new LinkedListNode ();
Newnode.info=input[i];
Newnode.link=null;
if (first==null) {
First=newnode;
Last=newnode;
}else{
Last.link=newnode;
Last=newnode;
}
}
}
return first;
}
public static void Main (string[] args) {
Int[] input={12,21,3,43};
Buildlistforward BLF = new Buildlistforward ();
LinkedListNode list=blf.buildlist (input);
while (List.link!=null) {
SYSTEM.OUT.PRINTLN ("list info:" +list.info+ "link:" +list.link);
List=list.link;
}
SYSTEM.OUT.PRINTLN ("list info:" +list.info+ "link:" +list.link);
}
}
Reverse construct linked list:
Package com.datastructrue.linkedTable;
public class Buildlistbackward {
Private LinkedListNode First,newnode;
int num;
Public LinkedListNode Buildlistbackward (int[] input) {
First=null;
if (input.length>0) {
for (int i=0;i<input.length;i++) {
Newnode=new LinkedListNode ();
Newnode.info=input[i];
Newnode.link=first;
First=newnode;
}
}
return first;
}
public static void Main (string[] args) {
int input[]={2,3,5,33};
Buildlistbackward blb=new Buildlistbackward ();
LinkedListNode list = Blb.buildlistbackward (input);
while (new Integer (List.info)!=null) {
System.out.println (List.info);
List=list.link;
// }
while (List.link!=null) {
System.out.println ("node:" +list.info);
List=list.link;
}
System.out.println (list.info+ "List.link:" +list.link);
}
}
Java linked list