java - 在Java中实现图表时出错

标签 java data-structures graph linked-list

我正在尝试使用 LinkedList 的 ArrayList 在 java 中创建一个图形。我已经实现了我自己的列表。然而,当我尝试在图的顶点之间添加连接时,我遇到了无限循环。我正在调试,我意识到当我尝试在 LinkedList 末尾添加元素时会发生这种情况。我是初学者,我不明白我的 List 实现有什么问题。有人可以帮忙吗?

import java.util.Stack;

// traverse the graph
public class GraphTraversal {


    public static void main(String[] args)
    {
        Graph graph=new Graph();
        initializeGraph(graph);
        graph.breadthFirstSearch();
    }

    public static void initializeGraph(Graph graph)
    {
        Node_Graph node1=new Node_Graph(1, false);
        Node_Graph node2=new Node_Graph(2, false);
        Node_Graph node3=new Node_Graph(3, false);
        Node_Graph node4=new Node_Graph(4, false);
        Node_Graph node5=new Node_Graph(5, false);
        Node_Graph node6=new Node_Graph(6, false);
        Node_Graph node7=new Node_Graph(7, false);
        Node_Graph node8=new Node_Graph(8, false);

        graph.addNode(node1);
        graph.addNode(node2);
        graph.addNode(node3);
        graph.addNode(node4);
        graph.addNode(node5);
        graph.addNode(node6);
        graph.addNode(node7);
        graph.addNode(node8);

        graph.makeConnection(node1, node2);
        graph.makeConnection(node1, node3);
        graph.makeConnection(node3, node4);
        graph.makeConnection(node3, node5);
        graph.makeConnection(node4, node5);
        graph.makeConnection(node4, node6);
        graph.makeConnection(node4, node8);
        graph.makeConnection(node4, node2);
        graph.makeConnection(node6, node5);
        graph.makeConnection(node8, node7);
        graph.makeConnection(node7, node2);
    }

}

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Stack;

//Class for graph data structure
public class Graph {

    public ArrayList<List> nodes=new ArrayList<List>();


    public void addNode(Node_Graph n)
    {
        List new_node=new List();
        new_node.add(n);
        nodes.add(new_node);
    }

    public void makeConnection(Node_Graph node1, Node_Graph node2)
    {

        for(List list:nodes)
        {
            if(list.head.getId()==node1.getId())
            {
                list.add(node2);
                break;
            }
        }
    }

    public void breadthFirstSearch()
    {
        Stack<Node_Graph> traverse=new Stack<Node_Graph>();
        Node_Graph start=(nodes.get(0)).head;
        start.setVisited(true);
        traverse.push(start);
        while(traverse.empty())
        {
            Node_Graph popped=traverse.pop();
            System.out.println(popped.getId());
            List nextList= nodes.get(popped.getId());
            Node_Graph newElement=nextList.head;
            while(newElement.getNext()!=null)
            {
                newElement=newElement.getNext();
                if(!newElement.getVisited())
                {
                    newElement.setVisited(true);
                    traverse.push(newElement);
                }
            }

            if(!newElement.getVisited())
                traverse.push(newElement);
        }
    }
}

//linked list implementation
public class List{
    public Node_Graph head;
    public int size; 

    public List()
    {
        head=null;
        size=0;
    }

    public void add(Node_Graph element)
    {
        if(head==null)
        {
            head=element;
        }
        else
        {
            Node_Graph last=head;
            while(last.getNext()!=null)
            {
                last=last.getNext();
            }
            last.setNext(element);
        }
    }
}

//node of a graph
public class Node_Graph {

    private int id;
    private boolean visited;
    private Node_Graph next;

    public Node_Graph(int id,boolean visited)
    {
        this.id=id;
        this.visited=visited;
    }
    public void setId(int id)
    {
        this.id=id;
    }

    public int getId()
    {
        return id;
    }

    public void setVisited(boolean visited)
    {
        this.visited=visited;
    }

    public boolean getVisited()
    {
        return visited; 
    }

    public void setNext(Node_Graph next)
    {
        this.next=next;
    }

    public Node_Graph getNext()
    {
        return next; 
    }
}

graph.makeConnection(node4, node6); 导致无限循环,因为节点 4 的下一个变量无限连接到节点 5

最佳答案

我注意到的第一件事是,graph.makeConnection(node3, node5); 行导致 4 连接到 5,这是不应该的。

我将 toString 方法添加到您的列表和 node_graph 类中,以尝试使其更容易理解正在发生的事情;它们在这里,您可以尝试一下:

列表:

public String toString(){
  Node_Graph h = head;
  String s = "";
  while(h != null){
    s += "[" + h.toString() + "] ";
    h = h.next;
  }
  return s;
}

节点图:

public String toString(){
  String s = id + "";
  if(next != null)
    s += ", " + next.toString();
  return s;
}

已找到错误。让我们从这一行开始:

graph.makeConnection(node1,node3);

这会导致调用: {1 -> 2,2 -> null}.add(3) 到目前为止一切顺利。

在 add 中,您找到列表的最后一个元素:{2},并将其设置在 {3} 的旁边。因此,列表现在看起来像 {1 -> 2 -> 3, 2 -> 3, 3},而它应该是 {1 -> 2 -> 3, 2, 3}。第一个列表(错误地)意味着 1 连接到 2 和 3,并且 2 连接到 3,而 2 不应该连接到 3,如第二个列表所示。在您当前的方案中,这是不可能的,因为“2”实际上是具有相同的单个 next 字段的同一对象。它不能是 1 元素中的 {3},而其自身不能是 {null}。

总的来说,您需要区分这两个“下一个”。我相信您的目标是,node_graph 中的下一个字段表示该节点连接到的节点,而列表中的下一个字段表示列表中的下一个节点,无论是否存在连接。你试图用一个石头和下一个字段来获得两只鸟,但它会以无限递归的方式回来咬你。

有很多更简洁的方法来实现图 - HashMap (节点 -> 邻居节点列表)更加简洁,可以让您免于处理所有接下来的业务。如果您的主要目标是完善图算法,例如 bfs/dfs-ing,您可能只想这样做。

如果您确实想使用列表来实现图表,那么您需要做一些整理工作。我建议从 Node_Graph 类中完全删除 next 字段; Node_Graph 类应该只关心它自己的数据,而不是维护列表不变量。然后使列表类具有一个内部包装类,其中包含“this”(Node_Graph 实例)和“next”(Node_Wrapper)实例。完成所有这些后,您可以为 Node_Graph 提供一个 List 类型的邻居字段,它将保存所有可访问的邻居。

这是一个遵循您的模式的基本 HashMap 图实现。您也不需要列表实现。不需要包装器/下一个:

public class Node{

    public final Graph graph; //The graph this Node belongs to 
    private int id;
    private boolean visited;

    /** Constructs a Node with the given inputs. 
      * Also adds itself to g as part of construction */
    public Node(Graph g, int i, boolean v){
        graph = g;
        id = i;
        visited = v;
        graph.addNode(this);
    }

    public int getId(){
        return id;
    }

    public void setVisited(boolean v){
        visited = v;
    }

    //Getters for boolean fields usually follow the is<Field> pattern
    public boolean isVisited(){
        return visited;
    }

    /** Looks up the neighbors of this in the graph */
    public Set<Node> getNeighbors(){
        return graph.neighborsOf(this);
    }
}

public class Graph{

    private HashMap<Node, HashSet<Node>> graph;  //The actual graph. Maps a node -> its neighbors

    public Graph(){
        graph = new HashMap<Node, HashSet<Node>>();
    }

    /** Adds the node to this graph.
        If n is already in this graph, doesn't overwrite */
    public void addNode(Node n) throws IllegalArgumentException{
        if(n.graph != this) 
            throw new IllegalArgumentException(n + " belongs to " + n.graph ", not " + this);
        if(! graph.contains(n))
            graph.put(n, new HashSet<Node>());
    }

    /** Returns the neighbors of the given node. 
      * Returns null if the node isn't in this graph */
    public Set<Node> neighborsOf(Node n){
        if(! graph.contains(n))
            return null;

        return graph.get(n);
    }

    /** Connects source to sink. Also adds both to graph if they aren't there yet */
    public void makeConnection(Node source, Node sink){
        //Make sure source and sink belong to this graph first
        addNode(source);
        addNode(sink);

        //Make the connection by adding sink to source's associated hashset
        graph.get(source).add(sink);
    }
}

关于java - 在Java中实现图表时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25226721/

相关文章:

java - JVM 垃圾收集应用程序停止时间差异

c - 处理 C 中的结构

c++ - 队列 <string&> 错误

python - 断字问题 - 创建数组/矩阵后如何继续?

algorithm - 如何找到树的任意两个顶点之间的边或顶点的数量?

graph - Graphviz/PyGraphviz 中的有向图的 NetworkX 样式 Spring 模型布局

具有自定义标准差的 Excel 图表

java - 如何创建按键事件

java - jsr 303(Bean Validation)是否有通用的约束库?

java - 为什么即使注释有 RetentionPolicy.RUNTIME,我的 isAnnotationPresent 方法也不起作用?