Singly-linked list/Element definition: Difference between revisions
Content added Content deleted
(→[[C]]: Corrected C example (C needs the struct tag, or alternatively a typedef; also a semicolon was missing; added C++) |
m (→[[C plus plus|C++]]: missing semicolon in C++ code and typo in text) |
||
Line 37:
int data;
link(int a_data, link* a_next = 0): next(a_next), data(a_data) {}
};
With this constructor, new nodes can be initialized directly at allocation; e.g. the
link* small_primes = new link(2, new link(3, new link(5, new link(7))));
|
Revision as of 08:51, 20 March 2007
![Task](http://static.miraheze.org/rosettacodewiki/thumb/b/ba/Rcode-button-task-crushed.png/64px-Rcode-button-task-crushed.png)
You are encouraged to solve this task according to the task description, using any language you may know.
Define the data structure for a singly-linked list element. Said an element should contain a data member capable of holding a numeric value.
Ada
type Link; type Link_Access is access Link; type Link is record Next : Link_Access := null; Data : Integer; end record;
C
struct link { struct link *next; int data; };
C++
The simplest C++ version looks basically like the C version:
struct link { link* next; int data; };
Initialization of links on the heap can be simplified by adding a constructor:
struct link { link* next; int data; link(int a_data, link* a_next = 0): 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))));
However, C++ also allows to make it generic on the data type (e.g. if you need large numbers, you might want to use a larger type than int, e.g. long on 64-bit platforms, long long on compilers that support it, or even a bigint class).
template<typename T> struct link { link* next; T data; link(int a_data, link* a_next = 0): next(a_next), data(a_data) {} };
Note that the generic version works for any type, not only integral types.