Which data structure to use for nodes in Java? - 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 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 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 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

Related

How to change the node in the built-in java LinkedList class to add a right and down pointer?

I have started to use Java. I want to use the built-in Java LinkedList class with my custom node class (my node class will contain fields: data, down pointer, right pointer). Is it possible to do so?
Here is my node class:
public class Node {
int data;
Node rt;
Node dw;
//constructor
public Node(int dataValue) {
rt=null;
dw=null;
data=dataValue;
}
//methods:
public int getData() {
return data;
}
public void setData(int dataValue) {
data = dataValue;
}
public void setrt(Node nextVal) {
rt=nextVal;
}
public void setdw(Node nextVal) {
dw=nextVal;
}
public Node getrt() {
return rt;
}
public Node getdw() {
return dw;
}
I created the following instance:
LinkedList h = new LinkedList<>();
I want to implement a 2D linked list using the built-in linked list class in java. To be able to do this i want to implement my custom node.
No, the node class of LinkedList is private, not exposed, you cannot access it. Except probably through some reflection hack.
And even if you could access the node class, you probably could not replace it with your own class. The LinkedList class is hardcoded to use its own node class.
If you really insisted, you could take the source code of the LinkedList class and modify it to use your node class. Please check if there are any license problems with such an approach before you do it, though. Also my gut feeling is that it’s not worth the trouble compared to writing your custom linked list class from scratch.
Java’s LinkedList is a doubly linked list, so each node has previous and next pointers and reference to data.
You can create a LinkedList of your own for this implementation.
But it looks like there are some basic things which you are doing wrong:
First, as per your implementation, you will be better off with Graph,
because what you are seeking is graph data structure, with each
vertex having four edges.
Second, you should not modify the existing data structures/collection
API provided by Java. If you really want to use different
data-structure, then create it and use it.
And the third and the most important thing to consider is that you
should always try to use the most efficient data-structures to solve a
problem. For example, you can create a 2-D Linkedlist, but ask
yourself, whether is it the most efficient one to store 2-D data? It
might happen that you could have used a matrix or a graph for storing the data.
Also, whenever you create or use a datastructure, consider whether
your application is read/write heavy, based on that you can optimize
storing and fetching of data.
But, it looks like you have just started, and so I would suggest just to go through basic data-structure books or online resources first.
You can also go through below URL which has similar requirement.
custom node class with java's linkedlist class

Is this a proper implementation of a Graph for DFS, BFS

I'm learning about search algorithms BFS and DFS. I plan to implement both but before I do that, I need to implement my graph structure. Here's my idea:
A graph of connecting cities: Each city is represented by a Node.
Our graph will simply be an ArrayList of Nodes added as they're created, and each Node will have a list of it's neighbors, and a parent which will let us know where we came from (for path retrieval). I haven't coded anything up yet, I wanted to get some feedback on my ideas before spending the time writing up something that won't work. Here's some pseudocode-ish, code. One potential problem I can see is how we're going to deal with Nodes that we can get to from multiple places (multiple parents). If anyone has any suggestions on dealing with that, feel free to share.
public class Node{
String name;
Node parent;
ArrayList<Node> neighbors;
public addNeighbor(Node n);
public setParent(Node n);
public getNeighbors()
...
}
public static void main(String[] args){
ArrayList<Node> graph = new ArrayList<Node>();
//build node
Node node = new Node(String name);
//add neighbors
node.addNeighbor(neighbor1);
node.addNeighbor(neighbor2);
//set parent
node.setParent(parent1);
//add to graph
graph.add(node);
path = dfs(graph, startNode, goalNode);
System.out.print(path);
}
Edit: I know I could look online and find implementations of this pretty easily, but I'd prefer to come up with my own solutions.
Your implementation look good. It's the classic implentation of a graph structure (a node with a list of neighbors). Some points:
You can use backtracking to deal with multiples paths that reach the same node. If the dfs method have a recursive implementation, you need to avoid the recursive call if the Node has already a parent. But if the new path is better that the old one, then you discard the old parent, and set the new one.
Your implementation is a directional graph. In other words, you can build a graph that has a path from A to B, but has no path from B to A. I don't know if this is ok for you.
I recommend you encapsulate the building of the graph inside a wrapper, that build both paths automatically, whith a unique call to a method. That way, always you build bidirectional paths.
You can use a Set to store the neighbors. That way, there is no duplicates. Of course, you need to implements the "equals" method in the Node class.

How to build in Java a Weighted Directed Acyclic Graph

I did a search on similar topics, but the answers are too vague for my level of understanding and comprehension, and I don't think they're specific enough to my question.
Similar threads:
Tree (directed acyclic graph) implementation
Representing a DAG (directed acyclic graph)
Question:
I have formatted a text file which contains data of the following format...
Example dataset:
GO:0000109#is_a: GO:0000110#is_a: GO:0000111#is_a: GO:0000112#is_a: GO:0000113#is_a: GO:0070312#is_a: GO:0070522#is_a: GO:0070912#is_a: GO:0070913#is_a: GO:0071942#part_of: GO:0008622
GO:0000112#part_of: GO:0000442
GO:0000118#is_a: GO:0016581#is_a: GO:0034967#is_a: GO:0070210#is_a: GO:0070211#is_a: GO:0070822#is_a: GO:0070823#is_a: GO:0070824
GO:0000120#is_a: GO:0000500#is_a: GO:0005668#is_a: GO:0070860
GO:0000123#is_a: GO:0005671#is_a: GO:0043189#is_a: GO:0070461#is_a: GO:0070775#is_a: GO:0072487
GO:0000126#is_a: GO:0034732#is_a: GO:0034733
GO:0000127#part_of: GO:0034734#part_of: GO:0034735
GO:0000133#is_a: GO:0031560#is_a: GO:0031561#is_a: GO:0031562#is_a: GO:0031563#part_of: GO:0031500
GO:0000137#part_of: GO:0000136
I'm looking to construct a weighted directed DAG from this data (the above is just a snippet). The whole dataset of 106kb is here: Source
--------------------------------------------------
Taking into consideration line-by-line, the data of each line is explained as follows...
First line as an example:
GO:0000109#is_a: GO:0000110#is_a: GO:0000111#is_a: GO:0000112#is_a: GO:0000113#is_a: GO:0070312#is_a: GO:0070522#is_a: GO:0070912#is_a: GO:0070913#is_a: GO:0071942#part_of: GO:0008622
'#' is the delimeter/tokenizer for the line data.
The First term, GO:0000109 is the node name.
The subsequent terms of is_a: GO:xxxxxxx OR part_of: GO:xxxxxxx are the nodes which are connected to GO:0000109.
Some of the subsequent terms have connections too, as depicted in the dataset.
When it is is_a, the weight of the edge is 0.8.
When it is part_of, the weight of the edge is 0.6.
--------------------------------------------------
I have Google-d on how DAGs are, and I understand the concept. However, I still have no idea how to put it into code. I'm using Java.
From my understanding, a graph generally consists of nodes and arcs. Does this graph require an adjacency list to determine the direction of the connection? If so, I'm not sure how to combine the graph and adjacency list to communicate with each other.
After constructing the graph, my secondary goal is to find out the degree of each node from the root node. There is a root node in the dataset.
For illustration, I have drawn out a sample of the connection of the first line of data below:
Image Link
I hope you guys understand what I'm trying to achieve here. Thanks for looking through my problem. :)
Because it's easier to think about, I'd prefer to represent it as a tree. (Also makes it easier to traverse the map and keep intermediate degrees.)
You could have a Node class, which would have a Collection of child Node objects. If you must, you could also represent the child relationships as a Relationship object, which would have both a weight and a Node pointer, and you could store a Collection of Relationship objects.
Then you could do a walk on the tree starting from the root, and mark each visited node with its degree.
class Node{
String name;
List<Relationship> children;
}
class Relationship{
Node child;
double weight;
}
class Tree{
Node root;
}
Here, Tree should probably have a method like this:
public Node findNodeByName(String name);
And Node should probably have a method like this:
public void addChild(Node n, double weight);
Then, as you parse each line, you call Tree.findNodeByName() to find the matching node (and create one if none exists... but that shouldn't happen, if your data is good), and append the subsequent items on the line to that node.
As you've pointed out, DAGs cannot really be converted to trees, especially because some nodes have multiple parents. What you can do is insert the same node as the child of multiple parents, perhaps using a hash table to decide if a particular node has been traversed or not.
Reading the comments, you seem confused by how a Node can contain Relationships which each in turn contains a Node. This is quite a common strategy, it is in general called the Composite pattern.
The idea in the case of trees is that the tree can be thought of as consisting of multiple subtrees - if you were to disconnect a node and all its ancestors from the tree, the disconnected nodes would still make a tree, though a smaller one. Thus, a natural way to represent a tree is to have each Node contain other Nodes as children. This approach lets you do many things recursively, which in the case of trees is often, again, natural.
Letting a Node keep track of its children and no other parts of the tree also emulates the mathematical directed graph - each vertex is "aware" only of its edges and nothing else.
Example recursive tree implementation
For instance, to search for an element in a binary search tree, you would call the root's search method. The root then checks whether the sought element is equal, less or greater than itself. If it is equal, the search exits with an appropriate return value. If it is less or greater, the root would instead call search on the left or right child, respectively, and they would do exactly the same thing.
Analogously, to add a new Node to the tree, you would call the root's add method with the new node as a parameter. The root decides whether it should adopt the new node or pass it on to one of its children. In the latter case, it would select a child and call its add method with the new Node as a parameter.

Storing objects in link lists

I've been asked to create and manage a link list from scratch without the use of the java util.
If I were to create an object which has more then one attribute e.g. name & age then would it be possible to store the object within the link list?
I'm having a hard time trying to get my head around this and would appreciate any help!
Here's my pseudo code:
Classes:
Node
LList
Person
Address
add_person
sout "Enter name"
scan.next(String name)
pass name to setName (a Person class function)
sout "Enter postcode"
scan.next(String postCode)
pass postCode to setPostCode (a Address class function)
How would I then go about linking these two bits of information together within the same link list?
Edit: Thanks for the input guys, I'll have a good read about based upon your recommendations! Once again many thanks! :)
Try looking up what a linked list is and how it needs to be constructed. Your psuedo code has nothing to do with a linked list, only some rudimentary data entry. I suggest you look over the following link to understand what it is and how it works. The actual coding is fairly simple once you understand the structure.
I encourage others to not do your homework for you.
Wikipedia
Its not too tough, you just need to create your own Node class. This class might look something like this:
public class Node{
protected String name;
protected int age;
//any additional data you need...
protected Node next;
//methods...
This class would contain many data fields and would provide methods to interact with these fields. The key component is the "protected Node next;" line, which is the next node in the linked list. All nodes in the list would have a next node, except for the tail. The tail node would set next equal to null.
First you need to define a basic building bloc of a linked list which is Node. Nodes are like containers that store whatever you want. That's why storedData variable is of type Object. You would define it like this:
public class MyNode{
Object storedData; // this is a reference to the object that you want stored in the list
MyNode next; //this is a reference to the next node in your list
...
}
Then you can define your linked list class, which would go like this:
public class MyLinkedList{
MyNode head; //this is a reference to the top element of your list
int nodeCount //
//put all the requkired methods here
}
You should write your own LinkedList that uses generics; let it handle any object type.
You name and post code and age and whatnot ought to be encapsulated in an object that you'd be able to add to the LinkedList.
package linkedlist;
public class Node<T> {
private Node<T> prev;
private Node<T> next;
private T value;
}

How do I create a binary tree with two int values?

I'm trying to create binary tree that contains two int values and one string value sorted in the lexicographic, but I'm not sure what to do. I've created an array list, which has been already sorted, but the binary tree has to be a reference-based which is not sorted and I'm thinking about sorting the list while creating it. Can any one help with this? Any brief idea would be appreciated.
Binary tree is a recursive thing. Make a class called BinaryTree (i hope you are in C++, or .NET or JAVA) that has two references to two other BinaryTrees (null by default). Then make an insert function that is recursive.
I don't know what you are trying to accomplish, but when building a binary tree, arrays are usually nowhere to be found.
You first should create a class to store your data and implement Comparable or use a Comparator.
public class Data { // Implement Comparable...
private String s;
private int n1;
private int n2;
// Implement constructors, getters, setters based on what you need...
// Implement compareTo (+ equals + hashCode) unless your going with Comparator
}
Then use a Collection that implements SortedSet to store your data, TreeSet is a good choice. The objects in the SortedSet are stored by reference so if you modify a value set in a local variable it will be modified in the collection as well.
Edit: If I understood your question about reference based lists correctly the following is possible in Java.
List<Data> dataList = // Create list and add data into it.
Data data = dataList.get(4);
data.setS(103); // Modifies S in the local data-object and in dataList because they are reference based.
It sounds like you already have a data structure to store your two int values and a string (since you have them sorted in an array list). You can include this data structure in a "tree node". A node typically has a reference pointer to a parent node (unless it is the root node) and 2 child nodes.
Since you want the tree to be sorted what you're really after is a special form of binary tree called a heap. The link to the Binary Heap wikipedia page below has an algorithm to show how to sort a binary heap.
http://en.wikipedia.org/wiki/Binary_heap
Here's some more general information on heaps and trees.
http://en.wikipedia.org/wiki/Binary_tree
http://en.wikipedia.org/wiki/Heap_(data_structure)
EDIT: You don't have to use a literal tree structure to store the your data in a tree form. It is perfectly acceptable to build a tree using an array. Instead of using reference pointers (parent and 1 or 2 child nodes) you can compute an index into the array. Each set of children is considered a "row" in the tree. The root element is on the zero row. It's two children are on the first row. The children of the root's children are on the second row, and so on.
Using this pattern the children of any node can be found using array[2*n+1] and array[2*n+2] where n is the row of the parent node. The parent of any node can be found by using array[floor( (n-1)/2)].

Categories