Jam*_*mes 86
(从评论中移出)
好吧,通过将自己限制为堆栈或队列方法(推,弹,移位,非移位),数组可以是堆栈或队列.使用push/pop提供LIFO(后进先出)行为(堆栈),而使用push/shift或unshift/pop给出FIFO行为(队列).
您可以使用类实现链接列表,但是数组将使用标准数组方法提供类似链接列表的行为.
div*_*yum 32
我猜大部分内容都包含在上面的答案中,但仅仅是为了更好地解释它的总结:
堆:
stack = []
stack << 2 # push 2 => stack = [2]
stack << 3 # push 3 => stack = [2, 3]
stack.pop # pop => 3, stack = [2]
Run Code Online (Sandbox Code Playgroud)
队列:
# 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
Run Code Online (Sandbox Code Playgroud)
链接列表:
# 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)
Run Code Online (Sandbox Code Playgroud)
地图:
# Hash incase of ruby
a = {} (or a = Hash.new)
a['one'] = 1 # a = {"one"=>1}
a['two'] = 2 # a = {"one"=>1, "two"=>2}
Run Code Online (Sandbox Code Playgroud)
组:
# 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
Run Code Online (Sandbox Code Playgroud)
是的,虽然没有明确的名义.的Array
类可被用作一个堆栈,队列或链表.例如,push
并pop
使其行为像堆栈.Ruby Map
就是这个Hash
类.Ruby也有一个Set
类,虽然你必须导入一个模块来使用它(require 'set'
).