# Algorithm of graph theory -- the realization of adjacency linked list of undirected graph

Keywords: Programming Java

# Introduction For example, there is such an undirected graph (it looks like a binary tree, but in fact, a binary tree is a special graph), which is represented by an adjacent list as follows: We use the index to represent the vertex, and the index points to a linked list (representing all the adjacent vertices of the vertex, for example, the adjacent vertices of vertex 2 are: 0,1,3). Because it is a undirected graph, if you add 0-2 edges, you will add 2 to the list corresponding to 0 and 0 to the list corresponding to 2.

# The realization of adjacency set of undirected graph

```package com.algorithms.graph;

import java.util.HashSet;
import java.util.Set;

/**
* Undirected graph
*
* Use 0 to V-1 to represent each vertex in a graph with V vertices.
*
*
* @author yjw
* @date 2019/5/15/015
*/
@SuppressWarnings("unchecked")
public class Graph {
/**
* Vertex number
*/
private int vertexNum;
/**
* Edge number
*/
private int edgeNum;

/**
* Adjacent set: parallel edges are not allowed
*/

public Graph(int v) {
this.vertexNum = v;
this.edgeNum = 0;
/**
* Represents vertices 0 to v-1
*/
for (int i = 0; i < v; i++) {
}
}

public int vertexNum() {
return vertexNum;
}

public int edgeNum() {
return edgeNum;
}

/**
* Add edge of V < - > W
* @param v
* @param w
*/
public void addEdge(int v,int w) {
/**
* Adding both ends is a undirected graph
*/
edgeNum++;
}
}

public void addEdge(int ... edges) {
if (edges.length % 2 != 0) {
throw new IllegalStateException("Number of vertices must be an integral multiple of 2");
}
for (int i = 0; i < edges.length -1; i+=2) {
}
}

/**
* Calculate the degree of v
* @param v
* @return
*/
public int degree(int v) {
int degree = 0;
for (int w : adj(v)) {
degree++;
}
return degree;
}

/**
* Returns the set of vertices from v
* @param v
* @return
*/
}

@Override
public String toString() {
StringBuilder s = new StringBuilder("(" + vertexNum + " vertices, " + edgeNum + " edges)\n");
for (int v = 0; v < vertexNum; v++) {
s.append(v).append(": ");
s.append(w).append(" ");
}
s.append("\n");
}
return s.toString();
}

public static void main(String[] args) {
Graph g = new Graph(6);
*/
System.out.println(g);
}
}

```

Instantiate undirected graph:

Through this method, we can easily construct the graph structure of the front structure.
```(6 vertices, 5 edges)