Doubly-linked list/Definition: Difference between revisions

Content added Content deleted
Line 600: Line 600:


=={{header|D}}==
=={{header|D}}==
<lang d>class LinkedList(T)
<lang d>import std.stdio;

class LinkedList(T)
{
{
Node!(T) head, tail;
Node!(T) head, tail;

/** Iterate in the forward direction. */
/** Iterate in the forward direction. */
int opApply (int delegate(uint, Node!(T)) dg)
int opApply (int delegate(uint, Node!(T)) dg)
Line 619: Line 621:
return result;
return result;
}
}

static LinkedList!(T) fromArray (T[] array)
static LinkedList!(T) fromArray (T[] array)
{
{
Line 641: Line 643:
LinkedList!(T) parent;
LinkedList!(T) parent;
T value;
T value;

this (Node!(T) next, Node!(T) previous, T value, LinkedList!(T) parent)
this (Node!(T) next, Node!(T) previous, T value, LinkedList!(T) parent)
in
in
Line 657: Line 659:
this.value = value;
this.value = value;
this.parent = parent;
this.parent = parent;

if (parent.head == next)
if (parent.head == next)
parent.head = this;
parent.head = this;
Line 663: Line 665:
parent.tail = this;
parent.tail = this;
}
}

/** Insert an element after this one. */
/** Insert an element after this one. */
void insertAfter (T value)
void insertAfter (T value)
{
{
new Node!(T)(this, next, value, parent);
new Node!(T)(next, this, value, parent);
}
}

/** Insert an element before this one. */
/** Insert an element before this one. */
void insertBefore (T value)
void insertBefore (T value)
{
{
new Node!(T)(previous, this, value, parent);
new Node!(T)(this, previous, value, parent);
}
}

/** Remove the current node from the list. */
/** Remove the current node from the list. */
void remove ()
void remove ()
Line 692: Line 694:
void main ()
void main ()
{
{
char[][] sample = ["was", "it", "a", "cat", "I", "saw"];
string[] sample = ["was", "it", "a", "cat", "I", "saw"];
auto list = LinkedList!(char[]).fromArray (sample);
auto list = LinkedList!string.fromArray (sample);
for (auto elem = list.head; elem; elem = elem.next)
for (auto elem = list.head; elem; elem = elem.next)
{
{