diff --git a/contents/stacks_and_queues/code/crystal/queue.cr b/contents/stacks_and_queues/code/crystal/queue.cr new file mode 100644 index 000000000..9f0a0b55b --- /dev/null +++ b/contents/stacks_and_queues/code/crystal/queue.cr @@ -0,0 +1,44 @@ +class Queue(T) + # The items in the queue. + @queue : Array(T) + + # Creates a new empty queue. + def initialize + @queue = Array(T).new + end + + # Pushes the given *item* onto the queue and returns the size of the queue. + def enqueue(item : T) + @queue << item + self.size + end + + # Removes the first item in the queue (at index 0). + def dequeue : T + @queue.shift + end + + # Returns the first item in the queue (at index 0). + def front : T + @queue[0] + end + + # Returns the number of items in the queue. + def size : Int32 + @queue.size + end +end + +def queue_example + queue = Queue(Int32).new + + queue.enqueue(4) + queue.enqueue(5) + queue.enqueue(9) + + puts queue.dequeue + puts queue.size + puts queue.front +end + +queue_example diff --git a/contents/stacks_and_queues/code/crystal/stack.cr b/contents/stacks_and_queues/code/crystal/stack.cr new file mode 100644 index 000000000..aaff55ea2 --- /dev/null +++ b/contents/stacks_and_queues/code/crystal/stack.cr @@ -0,0 +1,44 @@ +class Stack(T) + # The items in the stack. + @stack : Array(T) + + # Creates a new empty stack. + def initialize + @stack = Array(T).new + end + + # Pushes the given *item* onto the stack and returns the size of the stack. + def push(item : T) + @stack << item + self.size + end + + # Remove the last item from the stack. + def pop() : T + @stack.pop + end + + # Returns the number of items in the stack. + def size : Int32 + @stack.size + end + + # Returns the last item push onto the stack. + def top : T + @stack[-1] + end +end + +def stack_example + stack = Stack(Int32).new + + stack.push(4) + stack.push(5) + stack.push(9) + + puts stack.pop + puts stack.size + puts stack.top +end + +stack_example diff --git a/contents/stacks_and_queues/stacks_and_queues.md b/contents/stacks_and_queues/stacks_and_queues.md index 11c7088f7..691c64ce9 100644 --- a/contents/stacks_and_queues/stacks_and_queues.md +++ b/contents/stacks_and_queues/stacks_and_queues.md @@ -16,12 +16,16 @@ The notation for this depends on the language you are using. Queues, for example ## Example Code Here is a simple implementation of a stack: {% method %} +{% sample lang="crystal" %} +[import, lang:"crystal"](code/crystal/stack.cr) {% sample lang="ts" %} [import, lang:"typescript"](code/typescript/stack.ts) {% endmethod %} Here is a simple implementation of a queue: {% method %} +{% sample lang="crystal" %} +[import, lang:"crystal"](code/crystal/queue.cr) {% sample lang="ts" %} [import, lang:"typescript"](code/typescript/queue.ts) {% endmethod %}