java链式存储示例代码
时间: 2023-11-18 16:57:35 浏览: 24
以下是Java链式存储的示例代码:
```java
public class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
public class LinkedList {
Node head;
public LinkedList() {
this.head = null;
}
public void add(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
} else {
Node current = head;
while (current.next != null) {
current = current.next;
}
current.next = newNode;
}
}
public void display() {
Node current = head;
while (current != null) {
System.out.print(current.data + " ");
current = current.next;
}
}
}
```
其中,Node类表示链表中的节点,LinkedList类表示链表本身。在LinkedList类中,add()方法用于向链表中添加元素,display()方法用于打印链表中的所有元素。