I checked several Ruby tutorials online and they seemed to use array for everything. So how could I implement the following data structures in Ruby?
Understanding Stacks in Ruby What is a stack in Ruby? A stack is a data structure which you can use as a “to-do” list. You keep taking elements from the stack & processing them until the stack is empty.
A data structure is a specific way to organize & access data. Examples include: Arrays. Binary trees. Hashes.
Stack: Linked list: As a singly-linked list with a head pointer. Array: As a dynamic array.
(Moved from Comment)
Well, an array can be a stack or queue by limiting yourself to stack or queue methods (push, pop, shift, unshift). Using push / pop gives LIFO(last in first out) behavior (stack), while using push / shift or unshift / pop gives FIFO behavior (queue).
Maps are hashes, and a Set class already exists.
You could implement a linked list using classes, but arrays will give linked-list like behavior using the standard array methods.
I guess most of it is covered in above answers but just for summing it up for a better explanation:
Stack:
stack = [] stack << 2 # push 2 => stack = [2] stack << 3 # push 3 => stack = [2, 3] stack.pop # pop => 3, stack = [2]
Queue:
# we have a Queue class queue = Queue.new queue << 2 # push 2 => queue = [2] queue << 3 # push 3 => queue = [2, 3] (just a representation, it will be an object though) queue.pop # pop 2
Linked List:
# A very simple representation class Node attr_accessor :value, :next_node def initialize(value, next_node=nil) @value = value @next_node = next_node end end class LinkedList def initialize(value) @head = Node.new(value) end def add(value) current = @head while !current.next_node.nil? current = current.next_node end current.next_node = Node.new(value) end end ll = LinkedList.new ll.add(10) ll.add(20)
Maps:
# Hash incase of ruby a = {} (or a = Hash.new) a['one'] = 1 # a = {"one"=>1} a['two'] = 2 # a = {"one"=>1, "two"=>2}
Set:
# we have a Set class require 'set' s = Set.new # <Set: {}> s.add(1) # <Set: {1}> s.add(2) # <Set: {1, 2}> s.add(1) # <Set: {1, 2}> s.instance_of?(Set) # true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With