On Monday, 25 April 2022 at 01:40:01 UTC, Alain De Vod wrote:
Following program is a single linked list.
We expect as output 1 2 3 1 2 3
But the output is only 1 2 3
```

If you don't need List to be treated as a true range, but just want to iterate, a simple way to do this is with opApply:
https://tour.dlang.org/tour/en/gems/opdispatch-opapply
```d
import std.stdio: write,writeln;
import std.range: empty,popFront,front;

struct Node {
        int element;
        Node * next;
}

class List {
        Node * root=null;
        this(int[] AR){foreach(i ; AR)pushfront(i);}
        bool empty() const {return !root;}
        /*void popFront() {root=root.next;}
        float front() const {return root.element;}*/
        void pushfront(int element) {
                Node * newnode=new Node();
                newnode.element=element;
                newnode.next=root;
                root=newnode;
        }
        int opApply(int delegate(typeof(Node.element)) dg) {
                Node* current = root;
                while (current) {
if (dg(current.element)) return 1; // stop iteration if the foreach body asks to break
                        current = current.next;
                }
                return 0;
        }
}//List

void main(){
        List l=new List([3,2,1]);
        foreach(element; l) writeln(element);
        foreach(element; l) writeln(element);
}

// 1 2 3 1 2 3
```

Reply via email to