我最近遇到了一个有趣的链表实现(不幸的是不确定在哪里),Node
该类实现了插入和删除方法。以下是Node
双链表的类,但同样的原则也适用于单链表。
class Node
protected
attr_writer :prev, :next
public
attr_reader :value, :prev, :next
def initialize(value)
@value = value
end
def remove
@prev.next = @next if @prev
@next.prev = @prev if @next
@next = @prev = nil
end
def insert_after(node)
remove
@next = node.next
@next.prev = self if @next
@prev = node
node.next = self
end
end
我发现这个实现很有趣,因为我发现它非常通用。只需 aNode
即可开始构建列表并对其进行操作。
head = Node.new(1)
middle = Node.new(2)
middle.insert_after(head)
tail = Node.new(3)
tail.insert_after(middle)
middle.remove
在此实现之上,您可以构建一个更高级的 API,该 API 非常容易理解。以下是 a LinkedList
or的更完整版本Deque
。列表本身是列表的子类Node
并链接到列表的头部和尾部。
class ListNode < Node
protected :remove # prevent incorrect access to Node methods
def initialize
@next = @prev = self
end
def head
@next unless @next == self
end
def tail
@prev unless @prev == self
end
def add_to_head(node)
node.insert_after(self)
end
def add_to_tail(node)
node.insert_after(self.prev)
end
def each(&block)
return enum_for(:each) unless block_given?
node = @next
while node != self
yield node
node = node.next
end
end
def to_a
each.collect {|node| node.value }
end
end
以下是如何在实践中使用它:
# create a new list
list = ListNode.new
# add some items to the head or tail
list.add_to_head(Node.new('Hello'))
list.add_to_tail(Node.new('World'))
list.to_a # => ["Hello", "World"]
# remove items from the head
list.head.remove
list.to_a # => ["World"]
list.head == list.tail # => true
# remove items from the tail
list.tail.remove
list.to_a # => []
更好的是each
允许我们使用任何Enumerable函数来搜索和迭代节点的方法:
list = ListNode.new
list.add_to_head(Node.new(1))
list.add_to_head(Node.new(2))
list.add_to_head(Node.new(3))
list.add_to_head(Node.new(4))
# list each value
list.each {|node| puts node.value }
# select all nodes with values greater than 2
list.each.select {|node| node.value > 2 }
# find the first node with a value of 4
list.each.find {|node| node.value == 4 }