java没指针如何实现链表

avatar
作者
猴君
阅读量:0

在Java中,可以使用对象引用来实现链表。每个节点对象包含一个数据字段和一个指向下一个节点的引用字段。

首先,我们需要定义一个节点类,该类包含一个数据字段和一个指向下一个节点的引用字段。例如:

public class Node {     int data;     Node next;      public Node(int data) {         this.data = data;         this.next = null;     } } 

然后,我们可以定义一个LinkedList类来管理链表。该类包含一个指向链表头节点的引用字段和一些用于操作链表的方法。例如:

public class LinkedList {     Node head;      public LinkedList() {         this.head = null;     }      public void insert(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;         }     }      // 其他方法,比如删除节点、查找节点等等 } 

使用上述的Node和LinkedList类,我们可以创建一个链表并进行操作。例如:

public class Main {     public static void main(String[] args) {         LinkedList list = new LinkedList();          list.insert(1);         list.insert(2);         list.insert(3);          // 输出链表内容         Node current = list.head;         while (current != null) {             System.out.println(current.data);             current = current.next;         }     } } 

上述代码将创建一个包含3个节点的链表,并输出链表的内容:1,2,3。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!