Forgive me if this makes no sense at all, but I am just learning. I have stumbled across a piece of code that traverses a binary tree using a level search. I understand mostly the logic behind it but there are parts that confuse me, mainly 3 lines -
Node left, right; in the Node class. Am I correct that we are just making variables of this class type?
Node root; in the BinaryTree class. Is this an object of type Node? I thought you had to instantiate the class to have the object?
tree_level.root.left.right = new Node(5); I have no clue what is going on here. I understand that tree_level is the object and that through that object it can access the root variable, but then how is root able to access multiple left and right variables from the Node class.
I guess I'm more confused over how the two classes relate without any instantiation and I don't see any static code either.
package com.company;
import com.sun.xml.internal.ws.api.model.wsdl.WSDLOutput;
import org.w3c.dom.ls.LSOutput;
import java.util.Queue;
import java.util.LinkedList;
class Node{
int data;
Node left, right;
public Node(int item){
data = item;
left = null;
right = null;
}
}
public class BinaryTree {
Node root;
public void printLevelOrder(){
Queue<Node> queue = new LinkedList<Node>();
queue.add(root);
while(!queue.isEmpty()){
System.out.println("While loop starts...");
for(Node s : queue) {
System.out.println("Loop: " + s.data);
}
Node tempNode = queue.poll();
System.out.println(tempNode.data + " ");
if(tempNode.left != null){
queue.add(tempNode.left);
}
if(tempNode.right != null){
queue.add(tempNode.right);
}
}
}
public static void main(String[] args) {
BinaryTree tree_level = new BinaryTree();
tree_level.root = new Node(1);
tree_level.root.left = new Node(2);
tree_level.root.right = new Node(3);
tree_level.root.left.left = new Node(4);
tree_level.root.left.right = new Node(5);
System.out.println("The level order traversal of the binary tree is: ");
tree_level.printLevelOrder();
}
}
I'll try to answer your questions.
Node left, right; in the Node class. Am I correct that we are just making variables of this class type?
Yes, that's correct. After that declaration, your class Node has two new attributes Node left and Node right.
Node root; in the BinaryTree class. Is this an object of type Node?
Yes, this is an instantiation of a Node with the value null. From the Java Language Specification, section 4.12.5:
Initial Values of Variables
Every variable in a program must have a value before its value is used:
Each class variable, instance variable, or array component is initialized with a default > value when it is created
[...] For all reference types, the default value is null.
tree_level.root.left.right = new Node(5)
A new object of type Node is being placed inside a BinaryTree. This Node has a value of 5. In this case is something like this:
Related
I am working on a doubly linked list in Java. So that I can create functions, I'm first working to understand the setup.
I have this code. I have started comments with what each line does. Looking at tutorials and I want to make sure I understand this correctly. I still get a little confused on using classes.
If I create a new node by Node x = new Node(); - I am creating a new node of class Node. So that creates an instance using "static class Node {"
Each Node created contains a int item, Node next, and Node prev, that I will set in my functions. The int item I assume is the contents of the Node.
What does the line "public Node() {}" do?
public class MyDeque {
Node first = null; //instance variable, first is of type node and is set to null
Node last = null; //instance variable, last is of type node and is set to null
int N = 0; //keeping track of number of nodes
static class Node {
public Node() { }
public int item;
public Node next; //next is of type node
public Node prev; //prev is of type node
}
To understand this setup for Double-Linked-List you need to understand how a constructor works; A constructor is like a method, which is used to initialize properties of a class when the object of this class is initialized in memory for the first time.
Let's take your code for an example, I modified it in a proper way to understand why and how constructors used in Java -
public class MyDeque {
Node first;
Node last;
int N;
public MyDeque(){
this.first = null;
this.last = null;
this.N = 0;
}
static class Node {
int item;
Node next;
Node prev;
public Node() {
this.next = null;
this.prev = null;
}
public void setItem(int item) {
this.item = item;
}
public int getItem(){
return this.item;
}
// ... public getters for other items
}
As you can see two constructors public Node(){} and public MyDeque(){} are used to set values for the properties of those objects when they are initialized in memory for the first time.
Later, of course, you can set / unchange / change values of properties using the setter method or using the "." operator but remember constructor will always take place when the objects are initialized or reinitialized in memory for the first time.
Hi i am learning linked list in java. Its a simple doubt but couldn't figure out.
class Node{
int data;
Node next;
Node(int data){
this.data = data;
this.next = null;
}
//java main method
Node head = null;
Node newNode = new Node(1);
head.next = newNode;
Here i am passing the reference of the newNode to the next field in the Node class. The next is holding the reference of the newNode.
In dart programming languages objects are passed via call by value. By doing the above code is also working fine. My question is can we implement the Node field inside the Node class with either by reference or value.
In the context of c++, I don't know much c++ syntax but roughly it looks like this
//with pointer
class Node{
public:
int data;
Node* next;
}
It is possible to implement the above code like this one
//without pointer
class Node{
public:
int data;
Node next;
}
As stated by the other answers, your code wont work since your head variable is null and thus would throw a NullPointerException.
Your main method should like this:
Node head = new Node(0);
Node newNode = new Node(1);
head.next = newNode;
Java is always passing references by value. For a comprehensive answer see https://stackoverflow.com/a/40523/19799529
Pass-by-value
Java is always passing by value (as you are accustomed to):
int x = 3; f(x);
Object y = new Object(); g(y);
Above neither f nor g can alter the passed variables x and y.
The variables are just memory slots in which the value is stored, and that value is passed (not which memory slot), whether primitive type (int) or class instance (Object).
Linked list
Your Node class is fine.
public class SingleLinkedList {
Node head;
int count;
public int size() {
return count;
}
It is worth holding the Node inside a list class, possibly with a field for the number of elements. You could use that for index checking.
public void add(int i, int data) {
head = addToNodes(head, i, data);
++count;
}
private Node addToNodes(Node link, int i, int data) {
if (i <= 0 || link == null) {
Node node = new Node(data);
node.next = link;
return node;
}
link.next = addToNodes(link.next, i - 1, data);
return link;
}
Above I have used a recursive method. It shows that as the passed variable (head or some node's next field) cannot be changed in java, one has to return it assigning it to the same variable.
The code above is not very nicely formulated; write your own logic.
public class LinkedListExplained {
public Node head;
public Node tail;
public int size;
public LinkedListExplained() { // Constructor
head = null;
tail = null;
size = 0;
}
public class Node{ // Inner Class
String value;
Node next;
}
public void add(String value){
Node node = new Node();
node.value = value;
size++;
if (head == null){
head = node;
tail = node;
return;
}
tail.next = node;
tail = node;
}
Question, when storing a single String value to an empty LinkedList, does it store the same value twice?
Once as head and once as tail?
No. The head and tail variables point to the same Node object. That object contains the String once.
If you are learning Java, the first and foremost thing you need to understand is that in Java, everything that looks like an object is never actually an object; it is a pointer to an object. And of course two pointers may point to the same object.
So, the statement public Node head; does not declare an instance of Node. It declares a pointer to an instance of Node. That's why you have to use new Node(); later.
So, since you set both the head and the tail pointers to point to the same instance of Node, it might appear that you have two copies of that node, but in fact you do not. You only have one instance of Node, and you have two pointers pointing at it.
Hi it's been a while since I've written java and I can't seem to find what is wrong with this code. I'm implenting deleting a node from a linked list but my program won't compile. I keep getting:
error: non-static variable this cannot be referenced from a static context
Node head = new Node();
It has an error for all my new Node() instances in my main method.
public class NodeDelete{
class Node {
int data;
Node next;
public Node(){ }
}
Node Delete(Node head, int position) {
// Complete this method
int index = 0;
Node current = head;
if (position == 0 ){
head = head.next;
}
else{
while (index < (position - 1)){
current = current.next;
}
current.next = current.next.next;
}
return head;
}
public static void main(String[] args) {
Node head = new Node();
head.data = 0;
Node node1 = new Node();
node1.data = 1;
Node node2 = new Node();
node2.data = 2;
head.next = node1;
node1.next = node2;
}
}
Either make the Node class static. OR take out Node class from the NodeDelete class. That will solve the issue.
The Node class is a non-static inner class of NodeDelete, so it is like a member of the NodeDelete class. To access any member in the static context, instance of the class is required. That is why you are getting the compile time error here.
Note : The constructor you have defined in the Node is same as the default constructor. So no need to define it. It is redundant.
Making Node class static:
static class Node {
int data;
Node next;
public Node(){ } // This is same as the default constructor. So this can be remove.
}
OR
Take out the same implementation from the NodeDelete class.
Node is a non-static inner class. Therefore a instance of the containing class is needed to construct the instance:
NodeDelete nd = ...
Node node = nd.new Node();
Alternatives:
Make Node a static inner class
Make Node a top level class
Since there is no reference to a NodeDelete in Node's methods I recommend making Node static.
Another option not given yet, though not my favorite, would be to instantiate an instance of the class which contains the main method then use it to instantiate the inner class. Like so...
NodeDelete nd = new NodeDelete(...);
Node n = nd.new Node(...);
This question already has answers here:
Java final modifier
(2 answers)
Closed 8 years ago.
I was experimenting a bit in java and stumbled across this problem
Suppose i have a class with this recursive defination
public class Node<T> implements Iterable<T>{
public final T element;
public final Node<T> next;
public Node(T head, Node<T> tail) {
this.element = head;
this.next = tail;
}
// Contains few more methods and implementation of iteratable like add, remove etc
}
Now, the thing is I will be using this class as a field in another class with final keyword. Now if in the beginning i would be making an empty list and then add it to the list, how should i proceed.
TO make it simple
class NodeList <T>{
private final Node<T> head;
public NodeList(){
}
// Few more functions
}
Using NodeList class how can i create an empty list and later on add data using add function
In java reference works as pointer to an object in memory that internally can point to another one in the same way.
Let's try to understand it visually:
What happens to the pointer head when the object obj is added to an empty linked list?
You have to remove final keyword from head because it's reference that changes every time when new node is added to point the new node.
In below snapshot head is a reference that point to first object in the memory and first object contains another reference next that points to second object and so on...
how should i proceed.
create a new node
point next of new node to next of head
point head to new node
Sample code:
class Node<T> {
public final T element;
public final Node<T> next;
public Node(T head, Node<T> tail) {
this.element = head;
this.next = tail;
}
}
class NodeList<T> {
private Node<T> head;
public void add(T value) {
if (head != null) {
Node<T> node = new Node<T>(value, head); // create a new node
head = node; // point `head` to new node
} else {
// if head is null then assign it to head
head = new Node<T>(value, null);
}
}
}
NodeList<String> nodeList = new NodeList<String>();
nodeList.add("First");
nodeList.add("Second");
nodeList.add("Third");
// print all nodes
Node<String> node = nodeList.head;
while (node != null) {
System.out.println(node.element);
node = node.next;
}
output:
Third
Second
First
You cannot do it with the final keyword on the head attribute, since it will force you to initialize it during the instanciation : you should then initalize it to null to represent the empty list and won't be able to append an element to it. Remove the final keyword, it has no use there.
I'm not even convinced of the use of final in your Node class. What if you want to add or remove an element in the middle of the list ? Using final there limits considerably the number of operations you can perform on your data structure.