Singly-linked list/Element insertion: Difference between revisions

Content added Content deleted
(→‎{{header|Groovy}}: new solution)
(Updated D entry)
Line 266: Line 266:


=={{header|D}}==
=={{header|D}}==
<lang d>struct SLinkedNode(T) {
This is similar to C++ example.
T data;
typeof(this)* next;


this(T data_, typeof(this)* next_=null) {
<lang D>Node!(T) insert_element_after(T)(Node!(T) dst, Node!(T) src) {
src.next = dst.next;
this.data = data_;
dst.next = src;
this.next = next_;
return dst;
}
}
}</lang>


void insertAfter(T)(SLinkedNode!T* listNode, SLinkedNode!T* newNode) {
Sample usage (tango based):
newNode.next = listNode.next;
<lang D>void main()
listNode.next = newNode;
{
}
alias Node!(char[]) NodeStr;
auto a = new NodeStr("alpha", new NodeStr("bravo"));
auto c = new NodeStr("charlie");


void main() {
insert_element_after(a, c);
alias SLinkedNode!char N;


auto lh = new N('A', new N('B'));
// print out
while (a) {
auto c = new N('C');

Stdout(a.data) (" -> ");
// Inserts C after A, creating the (A C B) list:
a = a.next;
insertAfter(lh, c);
}

// gc will handle allocated memory
// The GC will collect the memory.
}</lang>
}</lang>