class Async::List
A double linked list.
def delete(item)
def delete(item) if @tail.equal?(item) @tail = @tail.tail else item.head.tail = item.tail end if @head.equal?(item) @head = @head.head else item.tail.head = item.head end item.head = nil item.tail = nil @size -= 1 return self end
def each(&block)
def each(&block) return to_enum unless block_given? current = self while node = current.tail yield node # If the node has deleted itself or any subsequent node, it will no longer be the next node, so don't use it for continued traversal: if current.tail.equal?(node) current = node end end end
def empty?
def empty? @tail.nil? end
def first
def first @tail end
def include?(needle)
def include?(needle) self.each do |item| return true if needle.equal?(item) end return false end
def initialize
def initialize # The list behaves like a list node, so @tail points to the next item (the first one) and head points to the previous item (the last one). This may be slightly confusing but it makes the interface more natural. @head = nil @tail = nil @size = 0 end
def insert(item)
def insert(item) unless @tail @tail = item @head = item # Consistency: item.head = nil item.tail = nil else @head.tail = item item.head = @head # Consistency: item.tail = nil @head = item end @size += 1 return self end
def last
def last @head end
def nil?
def nil? @tail.nil? end