class LinkedList::Singly

This is a singly linked list implementation.

Attributes

head[R]
length[R]

Public Class Methods

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

Public Instance Methods

each() { |data| ... } click to toggle source
# File lib/data_struct/linked_list.rb, line 83
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 93
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 103
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 48
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 37
def push(val)
  in_length
  return @head = SinglyNode.new(val) if @head.nil?

  node = @head
  (@length - 2).times do
    node = node.next_val
  end
  node.next_val = SinglyNode.new val
end
to_a() click to toggle source
# File lib/data_struct/linked_list.rb, line 73
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 63
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 32
def unshift(val)
  in_length
  @head = SinglyNode.new val, @head
end

Private Instance Methods

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