Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import std.stdio, std.algorithm, std.conv, std.array;
- class Stack(T) {
- private T[] data;
- private int max;
- public this() {
- data = new T[16];
- max = 0;
- }
- public auto push(T thing) {
- if (max == data.length) {
- data.length *= 2;
- }
- data[max] = thing;
- max++;
- return this;
- }
- public ref const(T) top() {
- return data[max-1];
- }
- public auto pop() {
- max--;
- if (max < data.length/4) {
- data.length /= 2;
- }
- return this;
- }
- public override string toString() {
- return "[ " ~ data[0..max].dup.reverse.map!(to!string).join(", ") ~ " ]";
- }
- public int size() {
- return max;
- }
- }
- class Queue(T) {
- private Stack!T stack1;
- private Stack!T stack2;
- public this() {
- stack1 = new Stack!T();
- stack2 = new Stack!T();
- }
- public auto enqueue(T thing) {
- while (stack2.size > 0) {
- stack1.push(stack2.top);
- stack2.pop;
- }
- stack2.push(thing);
- while (stack1.size > 0) {
- stack2.push(stack1.top);
- stack1.pop;
- }
- return this;
- }
- public ref const(T) front() {
- return stack2.top;
- }
- public auto dequeue() {
- stack2.pop;
- return this;
- }
- public override string toString() {
- return stack2.toString;
- }
- }
- void main() {
- Queue!int doopy = new Queue!int;
- writeln("Enqueuing 1 to 10.");
- foreach (x; 1..10) {
- doopy.enqueue(x);
- writeln(doopy);
- }
- writeln("Front: ", doopy.front);
- writeln("Dequeuing.");
- doopy.dequeue;
- writeln(doopy);
- writeln("Dequeuing again.");
- doopy.dequeue;
- writeln(doopy.front);
- writeln("Enqueuing 100.");
- doopy.enqueue(100);
- writeln(doopy);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement