Java中的链表如何实现
public class Test {
static ListNode first;//头节点
static ListNode current;//当前节点
public static void main(String[] args) {
for (int i = 1; i < 6; i++) {//往一个链表中加入1-5的元素
ListNode newNode = new ListNode(i);
if (first == null) {
first = newNode;
current = newNode;
} else {
current.next = newNode;
current = newNode;
}
}
System.out.println(first);
}
}
class ListNode {//节点
int data;//当前值
ListNode next;//下一个节点
public ListNode() {
}
public ListNode(int data) {
this.data = data;
}
@Override
public String toString() {
return "ListNode{" +
"data=" + data +
", next=" + next +
'}';
}
}
输出结果
ListNode{data=1, next=ListNode
{data=2, next=ListNode
{data=3, next=ListNode
{data=4, next=ListNode
{data=5, next=null}}}}}
理解
java中实现的链表,把它理解成一种嵌套更直观。第一步相当于初始化,头节点所作的更多是保存当前链表的数据。而后面增加节点,实际上是不断的改变当前节点的值,不断地嵌套,输出结果中那么多大括号也可以体现出来。
if (first == null) {
first = newNode;
current = newNode;
}