2013-05-10 88 views
1

我想弄清楚如何使一個鄰接列表,但無法理解我需要做什麼。我有這個Java代碼:試圖使用鏈接列表和向量使鄰接列表

public class Graph 
{ 
private final int V; 
private Bag<Integer>[] adj; 
public Graph(int V) 
{ 
this.V = V; 
adj = (Bag<Integer>[]) new Bag[V]; 
for (int v = 0; v < V; v++) 
adj[v] = new Bag<Integer>(); 
} 
public void addEdge(int v, int w) 
{ 
adj[v].add(w); 
adj[w].add(v); 
} 

但我想了解它,並將其轉換爲C++。我不確定的主要部分是

adj = (Bag<Integer>[]) new Bag[V]; 
for (int v = 0; v < V; v++) 
adj[v] = new Bag<Integer>(); 

任何人都可以幫助轉移到C++嗎?

回答

3

的Java:

adj = (Bag<Integer>[]) new Bag[V]; 
for (int v = 0; v < V; v++) 
adj[v] = new Bag<Integer>(); 

C++:

vector<vector<int>> adj; 
for(int v=0;v<V;v++) adj.push_back(vector<int>()); 

的Java:

public void addEdge(int v, int w) 
{ 
adj[v].add(w); 
adj[w].add(v); 
} 

C++:

public void addEdge(int v, int w) 
{ 
    adj[v].push_back(w); 
    adj[w].push_back(v); 
} 

一種M0 re:BigInteger可以存儲比int更大的數字。但是沒有必要使用BigInteger。因爲addEdge中的w和v必須小於V(V是一個int),否則它將溢出數組的範圍。