Engineering Full Stack Apps with Java and JavaScript
Basic building blocks of a linked data structure like linked list, trees, binary trees and graphs are nodes. All these data structures can be considered as a connection of these nodes. The structure of these nodes and how they are connected differ for different data structures. Hence to work with these data structures in Java, you need to understand their node structure first.
Here is a summary of nodes and their most commonly used structure, defined in Java.
package com.javajee.cse.dsa;
public class ListNode {
int data;
ListNode next;}
Variable next will point to the next node in a linked list.
package com.javajee.cse.dsa;
public class BTreeNode {
int data;
BTreeNode left, right;}
Every node will have pointers to its left and right child.
package com.javajee.cse.dsa;
import java.util.Collection;
public class TreeNode {
int data;
Collection<TreeNode> children;
}
A generic tree node may contain any number of childred. We can use any Collection to hold them.
package com.javajee.cse.dsa;
import java.util.Collection;
public class GraphNode {
int data;
Collection<GraphNode> adjacentNodes;
boolean visited;
}
A graph node will have pointers to its adjacent nodes. We can use any collection to hold the adjacent nodes. We can also use a bollean variable that can be used to see if a node is already visited while traversing, as graph can have circular links.