Singly-linked list/Element insertion: Difference between revisions

Updated D entry
(→‎{{header|Groovy}}: new solution)
(Updated D entry)
Line 266:
 
=={{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 this.nextdata = dst.nextdata_;
dst this.next = srcnext_;
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");
 
<lang D>void main() {
insert_element_after(a, c);
alias NodeSLinkedNode!(char[]) NodeStrN;
 
auto alh = new NodeStrN("alpha"'A', new NodeStrN("bravo"'B'));
// print out
whileauto c = new N(a'C') {;
 
Stdout(a.data) (" -> ");
// Inserts C after A, creating the (A C B) list:
a = a.next;
insertAfter(lh, c);
}
 
// gcThe GC will handlecollect allocatedthe memory.
}</lang>