class TrickBag::Collections::LinkedList

Linked List based on git@github.com:neilparikh/ruby-linked-list.git, but modified somewhat.

Attributes

first[RW]
length[R]

Public Class Methods

new(*items) click to toggle source

@param items items with which to initialize the list

# File lib/trick_bag/collections/linked_list.rb, line 22
def initialize(*items)
  @length = items.length
  @first = Node.new(items.shift)
  items.each { |item| push(item) }
end

Public Instance Methods

pop() click to toggle source

Returns the last element from the list and removes it @return the last element's value

# File lib/trick_bag/collections/linked_list.rb, line 45
def pop
  case(@length)

    when 0
      raise "List is empty"

    when 1
      @length = 0
      value = @first.value
      @first = nil
      value

    else
      current = @first
      while current.next && current.next.next
        current = current.next
      end
      value = current.next.value
      current.next = nil
      @length -= 1
      value
  end
end
push(value) click to toggle source

@param value value to add to end of list @return self

# File lib/trick_bag/collections/linked_list.rb, line 31
def push(value)
  node = Node.new(value)
  current_node = @first
  while current_node.next
    current_node = current_node.next
  end
  current_node.next = node
  @length += 1
  self
end
shift() click to toggle source

Removes the first element from the list @return the first element's value

# File lib/trick_bag/collections/linked_list.rb, line 83
def shift
  raise "List is empty" if @length < 1
  return_value = @first.value
  @first = @first.next
  @length -= 1
  return_value
end
to_a() click to toggle source

@return the values in this list as an array

# File lib/trick_bag/collections/linked_list.rb, line 93
def to_a
  current_node = @first
  array = []
  while current_node
    array << current_node.value
    current_node = current_node.next
  end
  array
end
to_ary() click to toggle source

@return the values in this list as an array

# File lib/trick_bag/collections/linked_list.rb, line 105
def to_ary
  to_a
end
unshift(value) click to toggle source

Adds a value to the beginning of the list @param value value to add to beginning of list @return self

# File lib/trick_bag/collections/linked_list.rb, line 73
def unshift(value)
  node = Node.new(value, @first)
  @first = node
  @length += 1
  self
end