Class: LinkedList::Singly

Inherits:
Object
  • Object
show all
Defined in:
lib/data_struct/linked_list.rb

Overview

This is a singly linked list implementation.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeSingly

Returns a new instance of Singly.



27
28
29
30
# File 'lib/data_struct/linked_list.rb', line 27

def initialize
  @head = nil
  @length = 0
end

Instance Attribute Details

#headObject (readonly)

Returns the value of attribute head.



26
27
28
# File 'lib/data_struct/linked_list.rb', line 26

def head
  @head
end

#lengthObject (readonly)

Returns the value of attribute length.



26
27
28
# File 'lib/data_struct/linked_list.rb', line 26

def length
  @length
end

Instance Method Details

#eachObject



83
84
85
86
87
88
89
90
91
# 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) ⇒ Object



93
94
95
96
97
98
99
100
101
# 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) ⇒ Object



103
104
105
106
107
108
109
110
111
# 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

#popObject



48
49
50
51
52
53
54
55
56
57
58
59
60
61
# 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) ⇒ Object



37
38
39
40
41
42
43
44
45
46
# 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_aObject



73
74
75
76
77
78
79
80
81
# 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_sObject



63
64
65
66
67
68
69
70
71
# 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) ⇒ Object



32
33
34
35
# File 'lib/data_struct/linked_list.rb', line 32

def unshift(val)
  in_length
  @head = SinglyNode.new val, @head
end