next Node in Node Class - java

I have this node class, I was wondering how does the program recognize that the Node next is actually the next node? and why would I want to assign it to null please? Detailed explanation would be greatly appreciated.
package LinearNode;
import dataobjects.*;
public class Node
{
public Node next;
public AnyClass obj;
public Node(AnyClass newObj)
{
next = null;
obj = newObj;
}
public void show()
{
System.out.println(obj.getData());
}
public void editNode()
{
obj.editData();
}
public Node getNext()
{
return next;
}
}

A Node is typically used in a linked list, and the node with a null next node is the last one of the list (since it doesn't have any next node).
The next node of a node will be the one you initialize, by doing
someNode.next = someOtherNode;
Note that fields should be private by default, and should almost never be public. Use methods to modify the state of objects.

It's the responsibility of the programmer to properly assemble and use the data structures he chooses. The next node points to a reference of what is assumed to be the 'next' node in the linked list, but Java can't tell you if you've linked them correctly or not. null is often used to represent the end of the list (as opposed to say a circular linked list, in which case head and tail pointers may be used instead of null). Documentation on the linked list data structure can be found on Wikipedia and also here, though the examples are written in C.

Related

Java member function for BST in order traversal

I recently was in a interview and was asked to code a in order traversal for a BST using the java member function prototype below.
public void inOrderPrint()
I was confused by the fact that it did not take in any parameters. I am used to the node to be passed in. It is very easy to traverse the tree with the node passed in... I am just a little confused how one would go about it without the initial reference?
The given signature makes sense if inOrderPrint() is defined in the Node class of the BST, then it's implied that the tree to traverse is the one rooted in the current node. Alternatively, it could be that the tree is an attribute in the current class. Assuming that the method is in the node class, it'd be something like this - and do notice how the recursion gets called:
public class Node {
private Node left;
private Node right;
private Object value;
public void inOrderPrint() {
if (left != null)
left.inOrderPrint();
System.out.println(value);
if (right != null)
right.inOrderPrint();
}
}
Given that it's a member function,one can assume that you have access to the root (e.g. this.root). You could just overload this method with a method where you pass in a node. You would then call the overloaded method inside the given one with the root.
EDIT:
I thought the method was defined in the tree, not in the Node class. You could do it like this: (make sure to check for null!)
public void inOrderPrint(){
//traverse down the left tree
this.left.inOrderPrint();
System.out.println(this);
//traverse down the right tree
this.right.inOrderPrint();
}

Explanation of a Java linked list class definition

I was given the following Java class definition to implement a single linked list program but I cannot get the full idea. I have written comments in the code poiting out my questions about it.
// ******************************************************************
// Definition of class Node<T>.
// ******************************************************************
public final class Node<T>
{
// This is a class with "generics" where T represents a type.
// A final class cannot be extended.
// A final variable behaves like a constant and can only be initialized at the time it is
// declared or within a constructor.
// I suppose this is the value of the node.
public final T v;
// I do not understand this. How is "next" defined "recursively"?
// Please help me visualize this situation.
// Can this variable indicate the end of the list, maybe with a null value?
public Node<T> next;
// Constructor.
public Node (T val, Node<T> link) {v = val; next = link}
}
// I suppose this is the value of the node.
public final T v;
Yes. Node is a parameterized class where the type of actual data it is holding is called T. So the value of the node is a variable having this type T. We could have a Node<Integer> which holds Integer value but also a Node<String> which would hold a String value. Node will behave the same way.
// I do not understand this. How is "next" defined "recursively"?
// Please help me visualize this situation.
// Can this variable indicate the end of the list, maybe with a null value?
public Node<T> next;
In a linked list, one node points to the next node in the list. This is why it is called "linked" list: there is a chain of elements all linked together. We might say it is defined recursively because one node points the next node, which in turn points to the next-next node, etc.
When the end is reached, there is no next node so it is null: the last element is the one having next = null. Note that there might not be a last element: one node could point to the first one and it would create a circular list.
As an example, let's say you want to build a linked list of 2 integer elements. The first element will be 1 followed by 3. You could write the following:
Node<Integer> firstElement = new Node<>(1, new Node<>(3, null));
// here firstElement.v will be 1 and firstElement.next.v will be 3

Java Programing Data field "head"

Im in a Java class at school and for the next program we have to edit a list. However there is one part of the instructions I don't understand.
Instructions from Homework:
It has a single data field "head" with the data type of MyNode, which is defined as follows:
public class MyNode<E extends Comparable<E>> {
E element;
MyNode<E> next;
public MyNode(E item) {
element = item;
next = null;
}
}
It contains a non-argument constructor that initialize head to be null.
I don't understand what my instructor means by "head"? Is he referring to the list as the "head"? Any ideas will help. Thank you.
That looks like the implementation of a linked list where each item (or node) contains a link to the next item (or node). Often the first item in a linked list is referred to as the 'head'.
So the instructions are asking you to write a class that contains a variable of type MyNode called head.
Something like this:
public class MyAnswer {
private MyNode head;
public MyAnswer() {
head = null;
}
}
In a linked list, head is the first element or node in the list. The head serves as an entry point to your list as you can reach any element (let's say the nth element) of the list by starting from head and accessing the next field of the node objects n times.

Node losing the reference to another object when passed through function

I'm working with double-ended queues for an assignment, and we're running into an issue where the object reference is disappearing from a node after being passed through an extremely simple method.
Some important definitions:
class Node {
String s;
Node prev;
Node next;
...
}
class Sentinel extends Node {
Node prev;
Node next;
//Constructor uses that of Node
}
class Deque {
Sentinel start;
...
}
One method we are writing removes a Node from a deque, based on the given string.
In deque:
public void removeSorted(String toRemove) {
// System.out.println(this.start);
// System.out.println(this.start.next);
this.start.next.removeSorted(toRemove);
}
The commented out println's show the correct Sentinel and Node.
Then, in Node:
public void removeSorted(String toRemove) {
if (this.s.equals(toRemove)) {
// System.out.println(this.prev);
// System.out.println(this.prev.next);
this.prev.next = this.next;
this.next.prev = this.prev;
} else if (this.s.compareTo(toRemove) > 0) {
throw new RuntimeException("String does not exist in these nodes!");
} else {
this.next.removeSorted(toRemove);
}
}
The println for this.prev outputs the Sentinel on the first recursion, as expected. However, this.prev.next outputs null instead of the Node.
This function only fails when trying to remove the first Node, directly after the Sentinel. If you try to remove any other Node, it works correctly, and trying to call this.prev.next results in a non-null answer.
Why does the reference disappear when passing to the function (immediately after), since we've shown that the reference is there directly before calling the function?
Either your question code is wrong, or you have same fields in both Node and in Sentinel. This means, that these two are different:
start.next is next field of Sentinel class, which hides field with same name from Node class.
start.next.prev.next is also a field of start, but now it is the field of Node class, because you access it through Node reference.
Remove prev and next from Sentinel. Actually remove the whole Sentinel, it looks like you use to to "remove" the String s, which is impossible, you can't "remove" super class fields. Or if you need/want sentinel, see below for alternative design.
Also, this demonstrates why you should use getters and setters instead of accessing fields directly... Your IDE probably has nice refactoring tool to add getters etc (right click on field, see "Refactor" submenu), use it! And if your IDE does not have that, switch to one which does (I prefer NetBeans, but Eclipse and IntelliJ are worthy too), writing Java without such an IDE is an exercise in masochism...
Also, in Java avoid that kind of inheritance. You should probably have this kind of overall design:
interface NodeInterface {...}
public class Node implements NodeInterface {...}
public class Sentinel implements NodeInterface {...}
Then in the NodeInterface, define getters and setters, which should take as parameters as well as return NodeInterface type. Sentinel class would not support all interface methods of course, so those methods can either return null;/do nothing, or throw new IllegalStateException("Sentinel does not support Xxxx."); depending on method and if calling that method for sentinel is bug in calling code or not (better start with throwing exception).
If this is school work and you have not gone over interfaces yet, then replace interface NodeInterface with class NodeBase (preferably abstract), but in "real world" this would be bad code, because Java does not support multiple inheritance.

Array of Linked Lists in Java

I have to create an array of linked lists for a class in order to store a graph (adjacency list). We have to use Java. I can create the array and instantiate each linked list, but when I go to add the first elements to each one, every linked list gets changed, not just the one at the index of the array.
Node [] adjList;
for(i=0;i<adjList.length;i++)
adjList[i] = new Node(0,0,null);
this instantiates each new linked list [Node is my own class, with constructor Node(int head, int data, Node next) and extends LinkedList]
then i go to add the first values to each node:
for(i=0;i<adjList.length;i++)
adjList[i].setHead(i+1); // numbers 1 to end are the graph vertices
or
for(i=0;i<adjList.length;i++)
adjList[i].add(new Node(i+1,0,null);
I use print statements to debug the code
at the end of these loop I print off each Linked List, but for each one, the values come out to be the final one
ie. if adjList.length = 2, it would print out
[3,0,null] // adjList[0]
[3,0,null] // adjList[1]
[3,0,null] // adjList[2]
edit: here is the Node class
import java.util.LinkedList;
public class Node extends LinkedList{
private static int head;
private static int data;
private static Node next;
public Node(int h,int d,Node n) {
head = h;
data = d;
next = n;
}
public int getHead(){ // getNext() and getData() are the same
return head;
}
public void setHead(int h){ // setNext() and setData() are basically the same
head = h;
}
}
You have probably declared something within Node as static, so every instance ends up with the same shared value, rather than having its own value. However, this is just a guess - please post the code of Node so we can see what the problem really is...
when I go to add the first elements to each one, every linked list gets changed, not just the one at the index of the array
Although your code snippet doesn't show it, almost definitely you have an aliasing problem. The aliasing problem, which tends to bite beginners in almost all object-oriented languages, is the problem of referring to the same object with two different names i.e. two different variables pointing at the same object.
Now you may be wondering: what about array indices? The problem is with changing a variable at one array index and getting a change across all array indices, not a bunch of named variables. But, as Eric Lippert explains (for C#, which is quite similar to Java), an array really is a bunch of variables that you can refer to with an indexer expression rather than having to define a bunch of individual names. In a sense, int[] foo = new int[3] is like declaring foo0, foo1, and foo2, and indexing into foo just tells the compiler to pick the appropriate variable out of foo0, foo1, and foo2.
You may also be wondering how data could be shared between multiple Node instances, if your array indeed has multiple nodes in it. There are a few ways, and knowing which is pretty much impossible without the code for the Node class. As #DNA points out, there could be static data in the Node class, which is automatically shared across all instances. A Node object may also have a reference to underlying data. If you pass the same reference into all the Node constructors, they are all aliasing the same object in this way as well.

Categories