Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class GraphAdjacentList {
- private Node listMatrix[];
- private int numVertices;
- class Node {
- public Node next;
- public int vertice;
- public Node(int v){
- this.vertice = v;
- }
- }
- public GraphAdjacentList(int numVertices) {
- this.numVertices = numVertices;
- listMatrix = new Node[numVertices];
- for (int i = 0 ; i < numVertices; i++) {
- this.listMatrix[i] = new Node(i);
- }
- }
- public void setEdge(int i, int j) {
- Node lastNode = null;
- lastNode = listMatrix[i];
- while (lastNode.next != null) {
- lastNode = lastNode.next;
- }
- lastNode.next = new Node(j);
- lastNode = listMatrix[j];
- while (lastNode.next != null) {
- lastNode = lastNode.next;
- }
- lastNode.next = new Node(i);
- }
- public void delEdge(int i, int j) {
- Node currNode = null;
- currNode = listMatrix[i];
- while (true) {
- if (currNode.next.vertice == j) break;
- if (currNode == null) break;
- currNode = currNode.next;
- }
- if (currNode != null) {
- currNode.next = currNode.next.next;
- }
- currNode = listMatrix[j];
- while (true) {
- if (currNode.next.vertice == i) break;
- if (currNode == null) break;
- currNode = currNode.next;
- }
- if (currNode != null) {
- currNode.next = currNode.next.next;
- }
- }
- public boolean isEdge(int i, int j) {
- Node currNode = null;
- currNode = listMatrix[i];
- while (true) {
- if (currNode == null) break;
- if (currNode.vertice == j) return true;
- currNode = currNode.next;
- }
- return false;
- }
- public int first(int v1){
- Node currNode = listMatrix[v1];
- int firstNeighborIndex = this.numVertices; // return n if none
- if (currNode.next != null){
- return currNode.next.vertice;
- }
- return firstNeighborIndex;
- }
- public int next(int v1, int v2){
- int firstNeighborIndex = this.numVertices; // return n if none
- Node currNode = listMatrix[v1];
- while (true) {
- if (currNode == null) break;
- if (currNode.vertice == v2 && currNode.next != null) return currNode.next.vertice;
- currNode = currNode.next;
- }
- return firstNeighborIndex;
- }
- public static void main(String[] args) {
- GraphAdjacentList gam = new GraphAdjacentList(5);
- boolean isEdge;
- gam.setEdge(0, 1);
- isEdge = gam.isEdge(0, 1);
- gam.delEdge(0, 1);
- isEdge = gam.isEdge(0, 1);
- gam.setEdge(0, 1);
- gam.setEdge(0, 2);
- gam.setEdge(0, 4);
- int nextNeighbor;
- nextNeighbor = gam.first(0);
- nextNeighbor = gam.next(0, nextNeighbor);
- nextNeighbor = gam.next(0, nextNeighbor);
- nextNeighbor = gam.next(0, nextNeighbor);
- System.out.print(gam.toString());
- System.out.println();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement