初学java构建简单的单链表
链表是一种最基本的结构,普通的单链表就是只给你一个只想链表头的指针head,如果想访问其他元素,就只能冲head开始一个个向后查找,遍历链表最终会访问尾节点,之后如果继续访问就会返回null。
链表的内部结构:
JVM构建链表的图示:
定义链表中的节点:
class Node{
//用data表示数据,nextNode表示下一节点.
public int data;
public Node nextNode;
//定义有参构造方法,方便创建节点时保存数据
public Node(int data) {
this.data = data;
}
定义一个整型数组:
int[] num = {4,15,7,40}
定义一个方法,用于将数组中的每一个元素分别放入一个新的节点中,然后完善节点形成单链表(这里使用最简单的枚举法实现单链表)
//创建方法initLinkedList(),使用枚举法将数组中每一个数据保存到一个新的节点中并按照数组中的顺序依次指定nextNode形成单链表,返回头节点。
private static Node initLinkedList(int[] num) {
Node head = null;
//创建新的节点,并将数据保存到节点中
Node node4 = new Node(num[3]);
Node node3 = new Node(num[2]);
Node node2 = new Node(num[1]);
Node node1 = new Node(num[0]);
//将node1作为头节点
head = node1;
//利用节点中的nextNode形成单链表
node1.nextNode = node2;
node2.nextNode = node3;
node3.nextNode = node4;
//返回头节点
return head;
}
}
完整代码如下:
package com.lanou;
public class example01 {
public static void main(String[] args) {
int[] num = {4,15,7,40};
Node node = initLinkedList(num);
System.out.println(node);
}
//创建方法initLinkedList(),使用枚举法将数组中每一个数据保存到一个新的节点中并按照数组中的顺序依次指定nextNode形成单链表,返回头节点。
private static Node initLinkedList(int[] num) {
Node head = null;
//创建新的节点,并将数据保存到节点中
Node node4 = new Node(num[3]);
Node node3 = new Node(num[2]);
Node node2 = new Node(num[1]);
Node node1 = new Node(num[0]);
//将node1作为头节点
head = node1;
//利用节点中的nextNode形成单链表
node1.nextNode = node2;
node2.nextNode = node3;
node3.nextNode = node4;
//返回头节点
return head;
}
}
class Node{
//用data表示数据,nextNode表示下一节点.
public int data;
public Node nextNode;
//定义有参构造方法,方便创建节点时保存数据
public Node(int data) {
this.data = data;
}
在“Node node = initLinkedList(num);”处加入断点进行debug调试获得结果如下图:
实现链表尾部添加节点
package com.lanou;
public class example01 {
public static void main(String[] args) {
int[] num = {1,2,3,4,5,6};
Node headNode = null;
//依次将数组num中的元素作为节点添加到尾部
for(int i =0;i<num.length;i++) {
headNode = insertNode(num[i], headNode);
}
System.out.println(headNode);
}
//定义方法insertNode()实现链表尾部添加节点
private static Node insertNode(int data,Node headNode) {
Node node = new Node(data);
Node node1 = headNode;
if(headNode == null) {
headNode = node;
return headNode;
}
while(true) {
if(node1.nextNode == null) {
node1.nextNode = node;
break;
}else {
node1 = node1.nextNode;
}
}
return headNode;
}
}
class Node{
public int data;
public Node nextNode;
public Node(int data) {
this.data = data;
}
}