在Java中,可以通過自定義類實現鏈表結構。以下是一個簡單的鏈表實現示例:
public class Node {
private int data;
private Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
public int getData() {
return data;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}
public class LinkedList {
private 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.getNext() != null) {
current = current.getNext();
}
current.setNext(newNode);
}
}
public void print() {
Node current = head;
while (current != null) {
System.out.print(current.getData() + " ");
current = current.getNext();
}
System.out.println();
}
public static void main(String[] args) {
LinkedList linkedList = new LinkedList();
linkedList.add(1);
linkedList.add(2);
linkedList.add(3);
linkedList.print();
}
}
該示例中,Node
類表示鏈表中的節點,包含一個整數數據和一個指向下一個節點的指針。LinkedList
類表示鏈表,包含一個指向頭節點的指針和一些基本操作方法,如添加節點和打印鏈表。在main
方法中,創建一個LinkedList
對象,并添加一些節點,然后打印鏈表中的數據。輸出結果為:1 2 3。