2017年7月29日 星期六

(Java) 圖形串列表示法

  1. import java.util.Arrays;  
  2. /* 
  3.  * 圖形串列表示法  
  4.  */  
  5. public class GraphLink {  
  6. Node frist ;  
  7. Node last ;  
  8. public static void main(String[] args) {  
  9.   int[][] am = {{1,2},{2,1},{3,2},{2,3},  
  10.              {4,2},{2,4},{1,5},{5,1},  
  11.              {5,3},{3,5},{5,4},{4,5},  
  12.              {3,4},{4,3}};//每個邊  
  13.   int[][] am2 = {{1,2},{2,3},{2,4},{4,3}};  
  14.   GraphLink[] g = new GraphLink[6];  
  15.   System.out.println("無向圖形");  
  16.     for(int i = 1 ; i < 6 ; i++){  
  17.      g[i] = new GraphLink();  
  18.      System.out.print("頂點"+i+"=>");  
  19.      for(int j = 0 ; j < 14 ; j++){  
  20.       if(i == am[j][0])   
  21.        g[i].Insert(am[j][1]);  
  22.         }  
  23.      g[i].print();  
  24.     }  
  25.     System.out.println("有向圖形");  
  26.     for(int i = 1 ; i < 6 ; i++){  
  27.      g[i] = new GraphLink();  
  28.      System.out.print("頂點"+i+"=>");  
  29.      for(int j = 0 ; j < 4 ; j++){  
  30.       if(i == am2[j][0])   
  31.        g[i].Insert(am2[j][1]);  
  32.         }  
  33.      g[i].print();  
  34.     }  
  35. }  
  36. public void Insert(int vertice){  
  37.  Node node = new Node(vertice);  
  38.  if(frist == null){  
  39.   frist = node ;  
  40.   last = frist ;  
  41.  }else{  
  42.   last.next = node ;  
  43.   last = node ;  
  44.  }  
  45. }  
  46. public void print(){  
  47.  Node curr = frist ;  
  48.  if(curr == null) System.out.print("空串列");  
  49.  while(curr != null){  
  50.   System.out.print(curr.vertice+" ");  
  51.   curr = curr.next ;  
  52.  }  
  53.  System.out.println();  
  54.    
  55. }  
  56. }  
  57. class Node{  
  58.  String j ;  
  59.  int vertice ;  
  60.  Node next ;  
  61.  Node(String j){  
  62.   this.j = j ;  
  63.  }  
  64.  Node(int v){  
  65.   vertice = v ;  
  66.  }  
  67. }  

沒有留言:

張貼留言

注意:只有此網誌的成員可以留言。