diff --git a/array-list.rb b/array-list.rb index a0d0342..0f1b66a 100644 --- a/array-list.rb +++ b/array-list.rb @@ -2,25 +2,52 @@ class ArrayList def initialize - @storage = [] + @storage = [nil,nil,nil,nil,nil] + @size = 0 end - def add(value) + def add(value) #like the push method in ruby. + @storage[@size] = value + @size += 1 end - def delete(value) + def delete#delete the last value + return nil if empty? + @size -= 1 end def display + @size.times do |i| + puts @storage[i] + end end def include?(key) + @size.times do |i| + if @storage[i] == key + return true + end + end + return false end def size + return @size end def max + return nil if empty? + biggest = 0 + @size.times do |i| + if @storage[i] > @storage[biggest] + biggest = i + end + end + return @storage[biggest] + end + + def empty? + @size ==0 end end @@ -37,5 +64,5 @@ def max arr.display puts "Delete 10 and then display the array list:" -arr.delete(10) +arr.delete arr.display diff --git a/linked-list.rb b/linked-list.rb index a1b30bd..f8a6506 100644 --- a/linked-list.rb +++ b/linked-list.rb @@ -5,9 +5,9 @@ class Node attr_accessor :value, :next_node - def initialize(val,next_in_line=null) + def initialize(val,next_in_line=nil) @value = val - @next_nodex = next_in_line + @next_node = next_in_line puts "Initialized a Node with value: " + value.to_s end end @@ -63,14 +63,45 @@ def display end def include?(key) + current = @head + #while we have nodes to traverse + while current != nil + #when we find the key + return true if current.value == key + #reassign currrent + current = current.next_node + end + puts "The list does not include #{key}" + return false end def size + @size = 0 + current = @head + while current != nil + #increase size + @size += 1 + #reassign current + current = current.next_node + end + puts "This linked list has #{@size} elements." + return @size end def max + current = @head + max_value = current.value + while current != nil + #if the current node has a larger value than the max gets reasigned + if current.value > max_value + max_value = current.value + end + #if max_value is larger than keep moving to check next node + current = current.next_node + end + puts "#{max_value} is the max value element in the list." + return max_value end - end # Initializing a Linked List with a node containing value (5) @@ -79,14 +110,28 @@ def max # Adding Elements to Linked List ll.add(10) ll.add(20) +# add more to list +ll.add(11) +ll.add(99) # Display the Linked List puts "Displaying Linked List:" ll.display +ll.include?(5) +# add more to test include? +ll.include?(11) +ll.include?(98) +ll.size +ll.max + puts "Delete 10 and then display the linked list:" ll.delete(10) ll.display +ll.size +ll.max + + =begin Output: