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
Related
private E value;
private Node <E> next; //this one
public Node( E newVal,Node <E> newNext) {
value = newVal;
next = newNext; //and this one
}
I'm really struggling to understand/visualize how the constructor is referencing the next Node by "next = newNext" and why must the variable type be identical to the class name.
Imagine a group of Letters (A,B,C,D). You want to arrange them as a list. One way to do so is the following: A comes first, and you tell A that letter after it is B (which is a letter). And then you tell B that the letter after it is C, etc. What you're doing here is linking the letters together.
Applying that concept to your case: Let's say you have a bunch of Nodes. A Node has a value of type E (E value), but in order for Nodes to be arranged as a list, you must tell each Node the Node that comes after it.
Hence when constructing a Node, you have to pass in a E newVal and a Node newNext, but remember in your case Node is parameterized over E. The Node you pass in must then also be parameterized over E, hence you pass in Node<E> newNext.
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.
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.
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.
class Nodetype
{
int info;
Nodetype next;
Nodetype(int i)
{
info=i;
next=null;
}
}
My textbook has this code to create Linked List dynamically.
The question is, when the programs is executed line-by line, it defines variable 'info' as type 'int' & then variable 'next' as Nodetype.
What is actually happening here?
does it mean that variable 'next' will contain -
Constructor 'Nodetype'
int info
Nodetype "next" where "next" will again have all 1,2,3 & then 3 will again have 1,2,3...and so on....till infinity?
I'm really irritated because I'm unable to understand how it works, can someone easily explain this?
Your code follows very well the definition of list: a list is null or an element followed by a list.
The "element", in your case, is defined by an int value, and the "followed by" part is the next variable; in Java variables (when they are not literals, as int values are) are actually pointers, so while they are not initialized they don't store any valid value and they don't point to any memory area (i.e. their value is null), so while the next variable is kept as-is your element is not followed by any other. To dynamically add elements to your list you need a pointer to the last element you added, otherwise you would not be able to find them again:
int i = 0;
Nodetype head = new Nodetype(i++);
Nodetype last = new Nodetype(i++);
head.next = last;
while (i<5) {
Nodetype temp = new Nodetype(i++);
last.next = temp;
last = temp;
}
while(head) {
System.out.println(head.info);
head = head.next;
}
Notice how, with the last few lines, you lose the head pointer and you have no way to get back the starting point of your list.. Keep that in mind when working with lists ;)
At first variable next doesn't point to any object(it points to null). At some time you will make it point to another node with next = new NodeType(number). The idea is that you use composition - you have one instance of class which has a reference to another instance. It is like nodeA points to nodeB, nodeB points to nodeC. Here you have three instances and the first instance has a reference to the second instance and the second instance has a reference to the third instance. The third instance is the last one and its next instance points to null.
the field next is a reference to an object of type Nodetype. at first it will point to nothing - since it is instantiated to null. when you assign a value to it, it will point to that value only, nothing will continue infinitely unless you create a cycle within the list.
You created class NodeType and inside of the class you defined object of that class. So that object (in your example next) will have int info variable NodeType next object and constructor.
It will contain Null, as the variable is not initialized to any value.
Nodetype is your class that defines the data a node instance will contain as well as the reference to the next node in the linked list. That reference to the next node will be an object of type Nodetype. Nothing too difficult here, this is the classic implementation of a Linked List.
You might want to check out this great linked list resource from Stanford.
The way this works is that the list is made up of single elements, each of which only has a pointer to the one that comes after it:
Nodetype next;
The information each element within the list actually holds is this:
int info;
You can think of a list like a "chain": it's not really a single object, but a compound object of a number of links. From each link, you can only see the next link (or, in case of linked lists that have references in both directions: the next and the previous link), so in order to have all elements available, you will have to keep the reference to the first element in the "chain".
Note: List objects are single objects that have a reference to the first link of the "chain".
next is a reference to another Nodetype instance. If next == null it means the current element is the last one in the list.
Let's see an example:
Nodetype node = new Nodetype(0); // i = 0, next = null
Nodetype anotherNode = new Nodetype(1); // i = 1, next = null
node.next = anotherNode; // now the first node has a ref to the second
#include<stdio.h>
#include<stdlib.h>
void print_list(int *arr,int *size,int *capacity)
{
printf("capacity = %d; size = %d; elements = ",*capacity,*size);
for(int i=0;i<(*size);i++){
printf("%d ",arr[i]);
}
printf("\n");
}
int * push_back(int *arr,int data,int *size,int *capacity)
{
int *b;
if(*size == *capacity){
*capacity = 2*(*capacity);
b = (int *)malloc(sizeof(int)*(*capacity));
for(int i=0;i<(*size);i++){
b[i]= arr[i];
}
b[*size]=data;
*size=*size+1;
print_list(b,size,capacity);
return b;
}
arr[*size]=data;
*size=*size+1;
print_list(arr,size,capacity);
return arr;
}
int main()
{
int size=0;
int n;
int x;
int *arr;
arr = (int *) malloc(sizeof(int));
int capacity=1;
scanf("%d",&n);
for(int i=0;i<n;i++){
scanf("%d",&x);
arr=push_back(arr,x,&size,&capacity);
}
}
its working.