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(...);
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.
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:
I am trying to create a linked list implementation using inner class
package linkedlist;
public class linkedList {
public class Node
{
int data;
public Node next;
public Node(int k)
{
this.data = k;
this.next=null;
}
public Node addToHead(int data)
{
Node node = new Node(data);
Node current = this;
node.next=current;
return node;
}
}
public static void findn(Node head)
{
Node previous=head;
Node current = head;
int i =1;
while(current!=null)
{
if (i==6)
{
//System.out.println(current.data);
previous.next = current.next;
break;
}
previous=current;
current = current.next;
i++;
}
}
public static void main(String args[])
{
linkedList list = new linkedList();
linkedList.Node tail = linkedList.new Node(0);
// list.Node tail = list.Node(0);
Node head = tail;
for (int i=1;i<=20;i++)
{
head = head.addToHead(i);
}
findn(head);
while(head!=null)
{
System.out.println(head.data);
head = head.next;
}
}
}
My question here in the main function i am trying to create a node using the outer class. But the syntax is throwing me an error even though i am following the right syntax. I want to know what is wrong with this statement
"linkedList.Node tail = linkedList.new Node(0);"
A Node, being a non-static inner class, needs an instance of its enclosing class. linkedList is the class name. It doesn't refer to an instance of the class. So it should be
list.new Node()
It would be much clearer if you respected the Java naming conventions: variables start with a lowercase letter, and classes with an uppercase letter.
You should probably create a method within class linkedList, addToTail():
public void addToTail(int k) {
Node tail = new Node(k);
//loop through all the nodes in the list and add "tail" to the end
}
Then you can call lst.addToTail(k) in main(), where lst would be an object of class linkedList.
BTW, it makes the code confusing to read when you begin class names with a lowercase letter. They usually start with an uppercase letter in Java. Calling the class LinkedList (starting with caps) is also confusing because it could be mistaken for the standard java.util.LinkedList, so perhaps you could call it LinkedList0 or something.