我已经为无向图和符号表编写了一个类,以将边从字符串转换为数字,反之亦然,但是由于出现堆栈溢出错误,因此这两个字符串方法不起作用。我已经实现了一个 LinkedStack,它与 java 库中的堆栈相同。我没有收到编译错误,如果可以查看 toString 方法,我将不胜感激。其他方法工作正常。这是下面的代码。我认为问题是当我调用迭代器时
public class EdgeWeightedGraph {
private final int V;
private int E;
private LinkedStack<Edge>[] adj;
public EdgeWeightedGraph(int V){
this.V = V;
this.E = 0;
adj = new LinkedStack[V];
for (int v = 0; v < V; v++)
{
adj[v] = new LinkedStack<Edge>();
}
}
public int V(){
return V(); // This was the error. thank you for spotting it :)
}
public int E(){
return E;
}
public int degree(int v){
return adj[v].size();
}
public void addEdge(Edge e){
int v = e.either();
int w = e.other(v);
adj[v].push(e);
adj[w].push(e);
E++;
}
public Iterable<Edge> adj(int v){
return adj[v];
}
public Iterable<Edge> edges(){
LinkedStack<Edge> b = new LinkedStack<Edge>();
for(int v = 0; v < V; v++)
{
for(Edge e: adj[v])
{
if(e.other(v) > v)
b.push(e);
}
}
return b;
}
}
至于包含 toString() 的其他类
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class EdgeSymbolGraph {
private ST<String, Integer> st;
private String[] keys;
private EdgeWeightedGraph G;
public EdgeSymbolGraph(File stream){
st = new ST<String, Integer>();
try
{
Scanner in = new Scanner(stream);
while(in.hasNextLine())
{
String v1 = in.next();
String v2 = in.next();
if(!st.contains(v1))
st.put(v1, st.size());
if(!st.contains(v2))
st.put(v2, st.size());
}
keys = new String[st.size()];
for(String name: st.keys())
keys[st.get(name)] = name;
G = new EdgeWeightedGraph(st.size());
Scanner m = new Scanner(stream);
for(int i = 0; m.hasNextLine(); i++)
{
int v1 = st.get(m.next());
int v2 = st.get(m.next());
Edge e = new Edge(v1, v2, i);
G.addEdge(e);
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
public EdgeWeightedGraph getGraph(){
return G;
}
public String name(int v){
return keys[v];
}
public int index(String s){
return st.get(s);
}
public String toString(){ //this the method that needs fixing
StringBuilder s = new StringBuilder();
s.append(G.V() + " " + G.E() + "\n");
for (int v = 0; v < G.V(); v++)
{
s.append(name(v) + " : ");
for (Edge e: G.adj(v)) // I think this is the problem when i call iterator
{
s.append(e.toString() + " ");
}
s.append("\n");
}
return s.toString();
}
}