Advertisement
Guest User

Untitled

a guest
Aug 26th, 2015
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
D 1.71 KB | None | 0 0
  1. import std.stdio, std.algorithm, std.conv, std.array;
  2.  
  3. class Stack(T) {
  4.   private T[] data;
  5.   private int max;
  6.  
  7.   public this() {
  8.     data = new T[16];
  9.     max = 0;
  10.   }
  11.  
  12.   public auto push(T thing) {
  13.     if (max == data.length) {
  14.       data.length *= 2;
  15.     }
  16.     data[max] = thing;
  17.     max++;
  18.     return this;
  19.   }
  20.  
  21.   public ref const(T) top() {
  22.     return data[max-1];
  23.   }
  24.  
  25.   public auto pop() {
  26.     max--;
  27.     if (max < data.length/4) {
  28.       data.length /= 2;
  29.     }
  30.     return this;
  31.   }
  32.  
  33.   public override string toString() {
  34.     return "[ " ~ data[0..max].dup.reverse.map!(to!string).join(", ") ~ " ]";
  35.   }
  36.  
  37.   public int size() {
  38.     return max;
  39.   }
  40.  
  41. }
  42.  
  43. class Queue(T) {
  44.   private Stack!T stack1;
  45.   private Stack!T stack2;
  46.  
  47.   public this() {
  48.     stack1 = new Stack!T();
  49.     stack2 = new Stack!T();
  50.   }
  51.  
  52.   public auto enqueue(T thing) {
  53.     while (stack2.size > 0) {
  54.       stack1.push(stack2.top);
  55.       stack2.pop;
  56.     }
  57.  
  58.     stack2.push(thing);
  59.  
  60.     while (stack1.size > 0) {
  61.       stack2.push(stack1.top);
  62.       stack1.pop;
  63.     }
  64.  
  65.     return this;
  66.   }
  67.  
  68.   public ref const(T) front() {
  69.     return stack2.top;
  70.   }
  71.  
  72.   public auto dequeue() {
  73.     stack2.pop;
  74.     return this;
  75.   }
  76.  
  77.   public override string toString() {
  78.     return stack2.toString;
  79.   }
  80. }
  81.  
  82. void main() {
  83.     Queue!int doopy = new Queue!int;
  84.  
  85.   writeln("Enqueuing 1 to 10.");
  86.   foreach (x; 1..10) {
  87.     doopy.enqueue(x);
  88.     writeln(doopy);
  89.   }
  90.   writeln("Front: ", doopy.front);
  91.  
  92.   writeln("Dequeuing.");
  93.   doopy.dequeue;
  94.   writeln(doopy);
  95.  
  96.   writeln("Dequeuing again.");
  97.   doopy.dequeue;
  98.   writeln(doopy.front);
  99.  
  100.   writeln("Enqueuing 100.");
  101.   doopy.enqueue(100);
  102.   writeln(doopy);
  103. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement