Singly-linked list/Element definition: Difference between revisions

Content deleted Content added
added ocaml
added java
Line 118:
 
but that would be really awkward to use.
 
=={{header|Java}}==
 
The simplest C++ version looks basically like the C version:
 
class Link
{
Link next;
int data;
}
 
Initialization of links on the heap can be simplified by adding a constructor:
 
class Link
{
Link next;
int data;
Link(int a_data, Link a_next) { next = a_next; data = a_data; }
}
 
With this constructor, new nodes can be initialized directly at allocation; e.g. the following code creates a complete list with just one statement:
 
Link small_primes = new Link(2, new Link(3, new Link(5, new Link(7, null))));
 
However, Java also allows to make it generic on the data type. This will only work on reference types, not primitive types like int or float.
 
class Link<T>
{
Link<T> next;
T data;
Link(int a_data, Link<T> a_next) { next = a_next; data = a_data; }
}
 
=={{header|OCaml}}==