class LinkedList
Attributes
length[R]
Public Class Methods
new()
click to toggle source
# File lib/linked_list.rb, line 6 def initialize @head = LinkedListNode.new @tail = LinkedListNode.new @head.next = @tail @tail.prev = @head @length = 0 end
Public Instance Methods
append(value)
click to toggle source
# File lib/linked_list.rb, line 23 def append(value) node = value.class == LinkedListNode ? value : LinkedListNode.new(value) old_last = @tail.prev old_last.next = node @tail.prev = node node.prev = old_last node.next = @tail @length += 1 node end
each() { |current| ... }
click to toggle source
# File lib/linked_list.rb, line 72 def each current = @head.next until current == @tail do yield current current = current.next end end
each_with_index() { |current, counter| ... }
click to toggle source
# File lib/linked_list.rb, line 81 def each_with_index current = @head.next counter = 0 until current == @tail do yield current, counter current = current.next counter += 1 end end
first()
click to toggle source
# File lib/linked_list.rb, line 15 def first @head.next == @tail ? nil : @head.next end
last()
click to toggle source
# File lib/linked_list.rb, line 19 def last @tail.prev == @head ? nil : @tail.prev end
map(&prc)
click to toggle source
# File lib/linked_list.rb, line 92 def map(&prc) prc ||= Proc.new { |node| node } current = @head.next result = [] until current == @tail do result << prc.call(current) current = current.next end result end
map_with_index(&prc)
click to toggle source
# File lib/linked_list.rb, line 105 def map_with_index(&prc) prc ||= Proc.new { |node, idx| node } current = @head.next counter = 0 result = [] until current == @tail do result << prc.call(current, counter) current = current.next counter += 1 end result end
pop()
click to toggle source
# File lib/linked_list.rb, line 49 def pop return nil if @head.next == @tail remove(@tail.prev) end
prepend(value)
click to toggle source
# File lib/linked_list.rb, line 36 def prepend(value) node = value.class == LinkedListNode ? value : LinkedListNode.new(value) old_first = @head.next old_first.prev = node @head.next = node node.next = old_first node.prev = @head @length += 1 node end
remove(node)
click to toggle source
# File lib/linked_list.rb, line 59 def remove(node) raise "Error in LinkedList#remove - given node is not a LinkedListNode, class is #{node.class}" unless node.class == LinkedListNode return if node == @tail || node == @head node.prev.next = node.next node.next.prev = node.prev node.prev = nil node.next = nil @length -= 1 node end
shift()
click to toggle source
# File lib/linked_list.rb, line 54 def shift return nil if @head.next == @tail remove(@head.next) end