下面是一个简单的Java单向链表的实现代码:
class Node { int data; Node next; public Node(int data) { this.data = https://www.yisu.com/ask/data;"hljs">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 printList() { Node current = head; while (current != null) { System.out.print(current.data + " "); current = current.next; } System.out.println(); } } public class Main { public static void main(String[] args) { LinkedList list = new LinkedList(); // 添加节点 list.addNode(1); list.addNode(2); list.addNode(3); list.addNode(4); // 打印链表 list.printList(); } }
在上面的代码中,Node
类表示链表的节点,其中包含一个data
变量表示节点的数据,以及一个next
变量表示指向下一个节点的引用。
LinkedList
类表示链表,其中包含一个head
变量表示链表的头节点。addNode
方法用于在链表末尾添加一个新节点,printList
方法用于打印链表的所有元素。
在Main
类的main
方法中,创建一个LinkedList
对象,然后调用addNode
方法添加节点,并最后调用printList
方法打印链表的元素。输出结果为:1 2 3 4。