Linked list, printing looks destructive.

Salih Dincer salihdb at hotmail.com
Mon Apr 25 05:17:28 UTC 2022


On Monday, 25 April 2022 at 02:19:46 UTC, Ali Çehreli wrote:
>
> This type violates a fundamental rule: Containers and ranges 
> are separate concepts. Your List is a container, not a range. I 
> changed your code by moving the range functions to a Range [...]

Dear Ali,

I implemented a linkedlist over classical logic (*_leaf and const 
*_root).  Now seeing the ranges approach I tried it but without 
success. The following implementation can work with foreach() 
though; as long as you call goRoot() :)

```d
class List(dType) {
   struct Node
   {
     dType item;
     Node* next;
   }
   bool FIFO;
   private Node * _leaf;

   this(bool FIFO = true, dType item = dType.init) {
     this.FIFO = FIFO;
     if(FIFO) _leaf= new Node(item, null);
     _root = cast(const)_leaf;
   }

   /*
   auto opSlice() { return Range(_leaf); }
   static struct Range {//*/
     const Node * _root;

     auto empty()
     {
       return !_leaf;
     }

     auto popFront()
     {
       return _leaf = _leaf.next;
     }

     dType front(Node * node = null)
     {
       dType result;
       if(node)
       {
         result = (*node).item;
       } else result = (*_leaf).item;

       return result;
     }
   //}

   alias Next = popFront;
   alias pop = front;
   alias push = InsertBack;

   void InsertBack(dType item)
   {
     _leaf = new Node(item, _leaf);
   }

   void InsertFront(dType item)
   {
     (*_leaf).next = new Node(item, null);
     Next;
   }

   auto goRoot()
   {
     return _leaf = cast(Node*)_root.next;
   }
}

import std.stdio;

enum FIFO { False, True }
enum end = 20;
void main()
{
   int firstNumber = 10;
   auto FIFO_Stack = new List!int;
   with(FIFO_Stack)
   {
     do {
       InsertFront(firstNumber);
     } while(++firstNumber <= end);

     goRoot();

     do pop.writef!"  %s"; while(Next);
     writeln;
   }

   FIFO_Stack.goRoot();

   foreach(stack; FIFO_Stack) {
     stack.writeln;
   }
} /* OUTPUT:
   10  11  12  13  14  15  16  17  18  19  20
10
11
12
13
14
15
16
17
18
19
20
*/
```
SDB at 79


More information about the Digitalmars-d-learn mailing list