Java单链列表示例
链接列表可以定义为随机存储在内存中的称为节点的对象的集合。
一个节点包含两个字段,即存储在该特定地址的数据和包含内存中下一个节点的地址的指针。
列表的最后一个节点包含指向null的指针。
程序:
public class LinkedListExamples
{
Node head;
// head of list
static class Node {
int data;
Node next;
Node(int d) {
data = d;
next=null;
}
}
/*
this function prints contents of the linked list starting from head
*/
public void display()
{
Node n = head;
while (n != null)
{
System.out.print(n.data+" \n");
n = n.next;
}
}
/*
method to create a simple linked list with 3 nodes
*/
public static void main(String[] args)
{
/*
Start with the empty list.
*/
LinkedListExamples list = new LinkedListExamples();
list.head = new Node(100);
Node second = new Node(200);
Node third = new Node(300);
list.head.next = second;
// Link first node with the second node
second.next = third;
// Link first node with the second node
list.display();
}
}
输出: