基本java:获取附加节点的列表

时间:2014-12-16 23:59:05

标签: java

所以我有一个基本节点列表,例如节点A B C。

每个组件都可以看到它所附加的内容,例如:

A-&GT,B

B-&以及c

C->一种

我想要一种方法,我可以获得图表中所有节点的列表。但是,我遇到了麻烦,因为我现在的系统无法检测到它是否已达到某一点。在上面的示例中,EG将是a-> b-> c-> a-> b等。如何检测这个或如何解决此问题。

我目前的解决方案" getList()班级中的Node

ArrayList<Node> tempList = new ArrayList<Node>();

    tempList.add(this);

    for(int i = 0 ; i < nodesAttachedTo.size();i++){
        tempList.addAll(nodesAttachedTo.get(i).getList());
    }

    return tempList;

3 个答案:

答案 0 :(得分:0)

您可以使用HashSet。它不允许一个元素添加两次。

这是一个示例代码,首先创建类似于您的示例的图形,然后从图形中的某个点开始并通过它。

import java.util.HashSet;

public class Node
{
    private HashSet<Node> nextNodes = new HashSet<Node>();

    public Node()
    {
    }

    public void addNextNode(Node node)
    {
        nextNodes.add(node);
    }

    public static void main(String[] args)
    {
        // this builds the graph of connected nodes
        Node a = new Node();
        Node b = new Node();
        Node c = new Node();

        a.addNextNode(b);
        b.addNextNode(c);
        c.addNextNode(a);

        //this is the set that will lsit all nodes:
        HashSet<Node> allNodes = new HashSet<Node>();

        // this goes through the graph
        a.listAllNodes(allNodes);

        System.out.println(allNodes);
    }

    private void listAllNodes (HashSet<Node> listOfNodes)
    {
        // try to put all next nodes of the node into the list:
        for(Node n : nextNodes)
        {
            if (listOfNodes.add(n))          // the set returns true if it did in fact add it.
                n.listAllNodes(listOfNodes); // recursion
        }

    }
}

这从一个节点到该节点知道的所有节点。 (说真快三次) 直到它遇到死胡同(=它已经访问过的节点)

我选择在Node本身中使用HashSet来存储它知道的所有节点。 这也可能是ArrayList或其他什么。但是因为我认为不应该有两次连接,所以在这种情况下HashSet似乎也是一个不错的选择。

答案 1 :(得分:0)

我不熟悉你的符号,但你可以使用两个指针来解决你的问题。从指向同一节点的两个指针开始。递增一个指针,直到它返回到开始。有些伪代码在下面。

ArrayList<Node> tempList = new ArrayList<Node>();
Node head = nodesAttachedTo.get(0); //get the head of the list
tempList.add(head);
Node runner = head;
runner = runner.next;
while (!runner.equals(head)) {
    tempList.add(runner);
    runner = runner.next;
}

答案 2 :(得分:0)

散列图可能就是这里的方法。它允许持续时间访问(需要一些开销,但我假设你想要一个可以很好地扩展的解决方案)到地图中的任何元素。

HashMap<String, String> specificSolution = new HashMap<String, String>();
specificSolution.put("a", "b");
specificSolution.put("b", "c");
specificSolution.put("c", "a");
// To get all nodes in the graph
Set<String> nodes = specificSolution.keySet();

我在这里用String实现了,因为你没有在你的问题中提供Node Class的定义,但它可以很容易地被换掉。

表示图表有许多不同的方法,每种方法都有自己的局限/优点。也许另一个可能更合适,但我们需要更多关于这个问题的信息。