2016-08-04 23 views
-2

Ich versuche, ein ungerichteten Graphen in Java zu implementieren mit Adjazenzliste aus der folgenden Ressource: http://www.geeksforgeeks.org/graph-and-its-representations/Wie Graph mit Adjazenzliste in Java implementieren

Der Code läuft ohne Fehler aber nicht gibt keine Ausgabe. Hier ist der Code:

class AdjListNode{ 
    int dest; 
    AdjListNode next; 

    public AdjListNode(int dest){ 
     this.dest = dest; 
     this.next = null; 
    } 
} 

class AdjList{ 
    AdjListNode head; 
} 

public class graph{ 
    int V; 
    AdjListNode newNode; 
    AdjList array[]; 

    public graph(int V){ 
     this.V = V; 
     this.array = new AdjList[V]; 
     int i; 
     for(i=0;i<V;++i){ 
      this.array[i].head = null; 
     } 
    } 

    void addEdge(graph g, int src, int dest){ 
     newNode = new AdjListNode(dest); 
     newNode.next = g.array[src].head; 
     g.array[src].head = newNode; 

     newNode = new AdjListNode(src); 
     newNode.next = g.array[dest].head; 
     g.array[dest].head = newNode; 
    } 

    void printGraph(graph g){ 
     int v; 
     for(v=0;v < g.V;++v){ 
      AdjListNode pCrawl = g.array[v].head; 
      System.out.println(); 
      System.out.println("Adjacency list of vertex "+v); 
      System.out.print("head"); 
      while(pCrawl != null){ 
       System.out.print(pCrawl.dest); 
       pCrawl = pCrawl.next; 
      } 
      System.out.println(); 
     } 
    } 

    public static void main(String[] args){ 
     int V = 5; 
     graph g = new graph(V); 
     g.addEdge(g,0,1); 
     g.addEdge(g,0,4); 
     g.addEdge(g,1,2); 
     g.addEdge(g,1,3); 
     g.addEdge(g,1,4); 
     g.addEdge(g,2,3); 
     g.addEdge(g,3,4); 

     g.printGraph(g); 
    } 
} 

Bitte helfen!

+0

Was ist der aktuelle Ausgang? – CMPS

+0

Ich bekam keine Ausgabe im Terminal. Aber in Eclipse hat es die 'NullPointerException' ausgelöst. –

+0

Ja, es wird erwartet! Ich habe das Update in meiner Antwort veröffentlicht – JavaHopper

Antwort

5

Sie haben keine Elemente mit in array initialisiert, bevor Sie einen Anruf an this.array[i].head tätigen. Daher würden Sie NullPointerExcpetion bekommen. Nach Updates sollte

arbeiten
public graph(int V){ 
    this.V = V; 
    this.array = new AdjList[V]; 
    int i; 
    for(i=0;i<V;++i){ 
     this.array[i] = new AdjList(); 
    } 
} 

Hinweis:

  1. Sie können Oracle folgen tutorial auf Arrays im Detail darüber, wie Arrays arbeiten in Java zu verstehen
  2. ich refactor andere Teile des Codes din't