Singly-linked list/Traversal: Difference between revisions

Content added Content deleted
No edit summary
(Updated first D entry)
Line 145: Line 145:


=={{header|D}}==
=={{header|D}}==
<lang d>struct SLinkedNode(T) {
Traversal using list defined in [[Singly-Linked_List_(element)#D | Singly-Linked list element - D]].
T data;
<lang D>// a is a beginning of a list);
typeof(this)* next;
while (a) {
Stdout(a.data) (" -> ");
a = a.next;
}</lang>


this(T data_, typeof(this)* next_=null) {
Or using tango's collections (written by Doug Lea, ported to D)
this.data = data_;
this.next = next_;
}
}


void main() {
<lang D>import tango.io.Stdout;
import std.stdio;

alias SLinkedNode!int N;
auto lh = new N(1, new N(2, new N(3, new N(4))));

auto p = lh;
while (p) {
write(p.data, " ");
p = p.next;
}
writeln();
}</lang>
{{out}}
<pre>1 2 3 4 </pre>
===Alternative Version===
Using tango's collections (written by Doug Lea, ported to D):
<lang d>import tango.io.Stdout;
import tango.util.collection.LinkSeq;
import tango.util.collection.LinkSeq;


Line 163: Line 181:
m.append("charlie");
m.append("charlie");
foreach (val; m)
foreach (val; m)
Stdout (val).newline;
Stdout(val).newline;
}</lang>
}</lang>