Advertisement
Guest User

Untitled

a guest
Dec 27th, 2024
440
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
D 1.98 KB | None | 0 0
  1. struct Stack(T)
  2. {
  3.     private SList!T container = null;
  4.     private Address pointer = 0;
  5.     private size_t length = 0;
  6.     private string name = null;
  7.  
  8.     this(string name)
  9.     {
  10.         this.name = name;
  11.     }
  12.  
  13.     void push(T value)
  14.     {
  15.         this.container.insertFront(value);
  16.         this.pointer++;
  17.         this.length++;
  18.     }
  19.  
  20.     Nullable!T topSafe()
  21.     {
  22.         Nullable!T front;
  23.         if (this.pointer > 0 && this.length != 0)
  24.             front = this.container.front();
  25.         return front;
  26.     }
  27.  
  28.     T top()
  29.     {
  30.         auto front_nullable = topSafe();
  31.         if (front_nullable.isNull)
  32.             throw new StackFlowError("The " ~ this.name ~ " stack underflew", this.pointer);
  33.         return front_nullable.get;
  34.     }
  35.  
  36.     T popTop()
  37.     {
  38.         auto front_nullable = topSafe();
  39.         if (front_nullable.isNull)
  40.             throw new StackFlowError("The " ~ this.name ~ " stack underflew", this.pointer);
  41.         this.container.removeFront();
  42.         this.pointer--;
  43.         this.length--;
  44.         return front_nullable.get;
  45.     }
  46.  
  47.     Nullable!T nthSafe(size_t n)
  48.     {
  49.         size_t n_prime = 0;
  50.         Nullable!T found;
  51.         foreach (elt; this.container.opSlice())
  52.         {
  53.             if (n_prime++ == n)
  54.             {
  55.                 found = elt;
  56.                 return found;
  57.             }
  58.         }
  59.         return found;
  60.     }
  61.  
  62.     T nth(size_t n)
  63.     {
  64.         auto nth_nullable = nthSafe(n);
  65.         if (nth_nullable.isNull)
  66.             throw new StackFlowError("The " ~ this.name ~ " stack overflew", this.pointer);
  67.         return nth_nullable.get;
  68.     }
  69.  
  70.     T popAtPointer()
  71.     {
  72.         auto nth = nth(this.pointer);
  73.         this.pointer--;
  74.         return nth;
  75.     }
  76.  
  77.     Address getPointer()
  78.     {
  79.         return this.pointer;
  80.     }
  81.  
  82.     void setPointer(Address pointer)
  83.     {
  84.         this.pointer = pointer;
  85.     }
  86.  
  87.     Address getLength()
  88.     {
  89.         return this.length;
  90.     }
  91. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement