Java输出邻接链表
时间: 2024-11-20 18:24:19 浏览: 28
在Java中,邻接链表通常用于表示图数据结构,特别是无向图或有向图中的顶点和它们之间的边。每个节点包含两个部分:一个存储关联的顶点值的数据域,以及一个指向下一个节点的引用。以下是创建并输出邻接链表的基本步骤:
1. 定义Node类,代表链表中的单个节点,包含一个顶点值(如整数、字符串等)和一个指向下一个节点的引用(通常是邻接列表的另一个Node对象)。
```java
class Node {
int vertex;
Node next;
// 构造函数
public Node(int v) {
vertex = v;
next = null;
}
}
```
2. 创建邻接链表类AdjListGraph,它维护一个Node类型的头节点,并提供添加边的方法。
```java
class AdjListGraph {
private Node head;
// 添加边的方法
public void addEdge(int src, int dest) {
Node newNode = new Node(dest);
if (head == null) {
head = newNode;
} else {
Node current = head;
while (current.next != null && current.vertex != src) {
current = current.next;
}
if (current.vertex == src) {
current.next = newNode;
} else {
System.out.println("Error: Edge not added properly.");
}
}
}
// 打印链表的方法
public void printList() {
Node current = head;
while (current != null) {
System.out.print(current.vertex + " -> ");
current = current.next;
}
System.out.println("null");
}
}
```
3. 使用示例:
```java
public static void main(String[] args) {
AdjListGraph graph = new AdjListGraph();
graph.addEdge(0, 1); // 添加从0到1的边
graph.addEdge(0, 2);
graph.addEdge(1, 2);
graph.printList(); // 输出链表
}
```
阅读全文
相关推荐

















