class LinkedList::Doubly

This is a Doubly linked list implementation.

Attributes

head[R]
length[R]

Public Class Methods

new() click to toggle source
# File lib/data_struct/linked_list.rb, line 126
def initialize
  @head = nil
  @length = 0
end

Public Instance Methods

each() { |data| ... } click to toggle source
# File lib/data_struct/linked_list.rb, line 187
def each
  node = @head
  arr = []
  @length.times do
    arr << yield(node.data)
    node = node.next_val
  end
  arr
end
index(index_val) click to toggle source
# File lib/data_struct/linked_list.rb, line 197
def index(index_val)
  raise 'index value higher than current length of list' if @length - 1 < index_val

  node = @head
  index_val.times do
    node = node.next_val
  end
  node.data
end
index_of(val) click to toggle source
# File lib/data_struct/linked_list.rb, line 207
def index_of(val)
  node = @head
  @length.times do
    return node.data if node.data == val

    node = node.next_val
  end
  raise 'value not found'
end
pop() click to toggle source
# File lib/data_struct/linked_list.rb, line 152
def pop
  node = @head
  if @length.zero?
    raise 'Error: List is empty'
  else
    de_length
    (@length - 1).times do
      node = node.next_val
    end
    node.next_val = nil
  end

  @head
end
push(val) click to toggle source
# File lib/data_struct/linked_list.rb, line 140
def push(val)
  in_length
  return @head = DoublyNode.new(val) if @head.nil?

  node = @head
  (@length - 2).times do
    node = node.next_val
  end
  node.next_val = DoublyNode.new val
  node.next_val.pre_val = node
end
to_a() click to toggle source
# File lib/data_struct/linked_list.rb, line 177
def to_a
  node = @head
  arr = []
  @length.times do
    arr << node.data
    node = node.next_val
  end
  arr
end
to_s() click to toggle source
# File lib/data_struct/linked_list.rb, line 167
def to_s
  node = @head
  str = ''
  (@length - 1).times do
    str += "#{node.data} "
    node = node.next_val
  end
  str
end
unshift(val) click to toggle source
# File lib/data_struct/linked_list.rb, line 131
def unshift(val)
  in_length
  return @head = DoublyNode.new(val) if @head.nil?

  new_head = DoublyNode.new val, nil, @head
  @head.pre_val = new_head
  @head = new_head
end

Private Instance Methods

de_length() click to toggle source
# File lib/data_struct/linked_list.rb, line 223
def de_length
  @length -= 1
end
in_length() click to toggle source
# File lib/data_struct/linked_list.rb, line 219
def in_length
  @length += 1
end