简体   繁体   中英

Which data structure to use for nodes in Java?

I want to create a class node, class Edge and class Graph. In class node, it must take some number as input to create nodes. Also, I want this class to have methods where I can change different attributes of the nodes. Also, it must contain a method to send and receive information from its adjacent nodes over Edge. These information receiving and sending methods should have provision to control information flow.

I am not sure which data structure to use for nodes to fulfill these requirements.

Create your own class node.

A node is just an object. Give it some attributes (for your example you probably want weight and value).

public class Node{

    private double weight;
    private String value;
    private ArrayList<Node> edges;


//setters and getters
}

Create a class Node that has all the attributes that you want. Ex. If you want to create a Node for a binary Tree your Node class can be something like.

  class Node
     {
        Node left;
        Node right;
        int info;
        Node(int value)
        {
         this.info = value;
        }
        //Add more attributes or functionalities
     }

This is one representation of how you can create a Node class . Depending upon your requirements the representation might change but the underlying concept remains the same.

Create a class Node which has a list of references to other Nodes (in a directed graph, this is especially usefull). An edge is not actually a "thing" to create - it's more like a connection.

The two most common ways to implement graphs are to use either an adjacency matrix or an adjacency list.

The matrix approach involves using a 2d array to determine if node i and node j are connected by asking if node[i][j] is true. Wasteful on space, but has constant time access.

Adjacency lists keep track of every adjacent node to the current node, which save on space but cost linear time in order to determine if a node is connected to it.

These articles explain it better:

Matrix

List

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM