Ruby Singly Linked List Implementation - ruby

I'd like to write an exist function that returns true if a value exists as a node in a linkedlist and returns false otherwise. So far, I have the following code which always returns true. Any help is appreciated:
class SinglyLinkedList
attr_accessor :head, :tail, :count
def initialize
#head = nil
#tail = nil
#count = 0
end
def insert_front(value)
node = Node.new(value)
if #head.nil?
#head = node
#tail = node
else
node.next = #head
#head = node
end
#count +=1
end
def print_first()
puts head.data
end
def print_last()
puts tail.data
end
def exist(value)
walker = #head
until walker.nil?
if walker.data == value
return true
end
walker = walker.next
end
false
end
def size()
count
end
end
class Node
attr_accessor :data, :next
def initialize(data)
#next = nil
#data = data
end
end
This is my test code:
list = SinglyLinkedList.new
list.insert_front(1)
list.exist(2)
which returns true.

Before solution just consider that singly linked list can insert only via append to list. You try to insert nodes in wrong direction.
The problem with you code is that you use reserved method name next, just refactor you code and write simple:
class SinglyLinkedList
class Node
attr_reader :value
attr_accessor :pointer
def initialize(value, pointer = nil)
#value = value
#pointer = pointer
#count = 0
end
end
attr_reader :head, :tail
def initialize
#head = nil
#tail = nil
end
def insert(value)
node = Node.new(value)
#count += 1
if #head.nil?
#head = node
#tail = node
else
#tail.pointer = node
#tail = node
end
end
def inspect
return [] unless #head
values = []
node = #head
begin
values << node.value
node = node.pointer
end while node != nil
values
end
def exists?(value)
return false unless #head
node = #head
begin
node = node.pointer
end while node != nil && node.value != value
node.nil?
end
end

Related

Ruby Binary Search Tree insert method stack level too deep

I am trying to write a recursive insert method for a binary search tree but keep getting stack level too deep What is going on that it keeps giving me the error?
my node class
class Node
attr_accessor :value, :left, :right
def initialize(value)
#value = value
left = nil
right = nil
end
end
binary search tree class
class Bst
attr_accessor :root, :size
def initialize
#root = nil
#size = 0
end
def insert(value, root=nil)
if #root == nil
#root = Node.new(value)
end
if value < #root.value
if #root.left == nil
#root.left = Node.new(value)
else
return insert(value, #root.left)
end
return root
end
if value > #root.value
if #root.right == nil
#root.right = Node.new(value)
else
return insert(value, #root.right)
end
end
return root
end
It happens once I try to add 4 to the tree
tree = Bst.new
tree.insert(10)
tree.insert(6)
tree.insert(19)
tree.insert(4)
When you recurse and provide new root, you are still comparing the value with #root.value.
Since 4 is still less than 10, you recurse, and pass #root.left as root. However, root is never used; you are again comparing #root.value, and recursing with #root.left, and those never change; thus, you have infinite recursion (or at least infinite till you blow the stack).
You want to be comparing to root.value, and recursing with root.left instead.
Having #root and root be different things is confusing, and leads to logic errors. Better variable naming would likely have prevented this error.
EDIT:
class Node
attr_accessor :value, :left, :right
def initialize(value)
#value = value
#left = nil
#right = nil
end
end
class Bst
attr_accessor :root, :size
def initialize
#root = nil
#size = 0
end
def insert(value, node=nil)
unless #root
#root = Node.new(value)
return
end
node ||= #root
if value < node.value
if node.left
return insert(value, node.left)
else
node.left = Node.new(value)
end
elsif value > node.value
if node.right
return insert(value, node.right)
else
node.right = Node.new(value)
end
end
#size += 1
return node
end
end
tree = Bst.new
tree.insert(10)
tree.insert(6)
tree.insert(19)
tree.insert(4)
p tree

Within a Linked List in Ruby, the method add_at with index is not working right

I am studying Ruby, and this Linked list exercise is a little complicated for me, I advanced, but not sure what I am doing wrong:
class Node
attr_accessor :value, :next_node
alias_method :next, :next_node
def initialize(value, next_node = nil)
#value = value
#next_node = next_node
end
def next
#next_node
end
end
class LinkedList
attr_accessor :head, :tail
def initialize
#head = nil
#tail = nil
end
def add(number)
if #head.nil?
new_node = Node.new(number)
#head = new_node
#tail = new_node
else
new_node = Node.new(number)
#tail.next_node = new_node
#tail = new_node
end
end
def get(index)
current = #head
index.times do
current = current.next_node
end
return current.value
end
def add_at(index, item)
current = head
(index - 1).times do
raise "List not long enough" if current.nil?
current = current.next_node
end
new_node = Node.new(item)
new_node.next_node = current.next_node
current.next_node = new_node
end
end
Tried to change the Node method, but seems like that is not the answer
Everything seems fine to me, but the data is not sorted in the right position according the following test:
list = LinkedList.new
list.add(3)
list.add(5)
list.add_at(1, 11)
list.add_at(0, 13)
puts list.get(#)
should be 13,3,11,5 at the end
Am I doing something wrong?
Your LinkedList#add_at method does not work correctly when inserting to the beginning (or end) of the list.
In particular, when calling list.add_at(0, 13), where's what happens:
def add_at(index, item)
current = head # Current is set to the "3" node
(index - 1).times do # This never yields
raise "List not long enough" if current.nil?
current = current.next_node
end
new_node = Node.new(item) # Creates the "13" node
new_node.next_node = current.next_node # "13" points to "11"
current.next_node = new_node # "3" points to "13"
end
Result: Instead of turning 3 --> 11 --> 5 into 13 --> 3 --> 11 --> 5, you've turned it into 3 --> 13 --> 11 --> 5.
In other words, the end result of calling list.add_at(0, 13) is the same as calling list.add_at(1, 13).
I don't want to dictate a single solution to you here; the key takeaway should be how to debug the problem. For example, you could try installing pry, add binding.pry into the method and step through the code to reproduce my summary.
This is an absolutely vital developer skill that's needed to solve problems of this manner.
...But with that said, here's a suggestion: Re-use the existing methods to fetch the previous and next nodes; then re-set the head/tail values if necessary (as well as "inserting" the new node into the list):
def add_at(index, item)
new_node = Node.new(item)
previous_node = get(index-1)
next_node = get(index)
if previous_node
previous_node.next_node = new_node
else
head = new_node
end
if next_node
new_node.next_node = next_node
else
tail = new_node
end
end

how to code to_s (toString) method for Linked list

I am trying to implement a singly Linked List in Ruby and it works fine until I try to delete all the elements to the list. Deleting the elements seems to work but deleting the last element and calling a to_s method causes a runtime error even though I tried to traverse the list while the next Item is not equal to nil.
Here's my code:
#----- NODE CLASS -----#
class Node
attr_accessor :data, :link # automatically generated getters & setters
# Constructor/Initializer #
def initialize(data = nil, link = nil)
#data = data
#link = link
end
# toString method #
def to_s
#data
end
end #End node class
#----- AbstractList Class -----#
class AbstractList
##listSize
def getSize
return ##listSize
end
# Constructor/Initializer #
def initialize()
#head = nil
##listSize = 0
end
# insert at the front of the list #
def insertFront(item)
if #head == nil
#head = Node.new(item)
else
temp = Node.new(item)
temp.link = #head
#head = temp
end
##listSize += 1
end
# insert at the front of the list #
def insertBack(item)
if #head == nil
#head = Node.new(item)
else
current = #head
while current.link != nil
current = current.link
end
newNode = Node.new(item, nil)
current.link = newNode
end
##listSize += 1
end
# remove from the front of the list #
def removeFront()
if empty()
raise "List is empty"
end
current = #head
#head = #head.link
current = nil
##listSize -= 1
end
# check if list is empty #
def empty()
result = false
if ##listSize == 0
result = true
end
return result
end
# toString method #
def to_s
result = []
current = #head
while current.link != nil
result << current.data
current = current.link
end
result << current.data
return result
end
end #End AbstractList class
#----- MAIN METHOD -----#
#node = Node.new("Ten", "twenty")
#print node.to_s
list = AbstractList.new()
list.insertFront("One")
list.insertFront("Two")
list.insertFront("Three")
list.insertFront("Four")
list.insertBack(10)
list.insertBack(20)
list.insertBack(30)
list.insertBack(40)
print list.to_s
puts " List size => #{list.getSize}"
list.removeFront()
list.removeFront()
list.removeFront()
list.removeFront()
list.removeFront()
list.removeFront()
list.removeFront()
print list.to_s
puts " List size => #{list.getSize}"
list.removeFront()
It prints out the following and causes an error when I remove the last element and print:
>["Four", "Three", "Two", "One", 10, 20, 30, 40] List size => 8
>[40] List size => 1
>List size => 0
>in `to_s': undefined method `link' for nil:NilClass (NoMethodError)
and the error points to the line
while current.link != nil
in the to_s method of the Abstract list.
When last element is deleted then #head is set to nil
Now, you are calling to_s on list
def to_s
result = []
current = #head
while current.link != nil
result << current.data
current = current.link
end
result << current.data
return result
end
Here current = #head which is assigned to nil
In next step, while current.link != nil , it will check link for nil which is throwing an error.
Solution : change your while condition to while current and current.link != nil
def to_s
result = []
current = #head
while current and current.link != nil
result << current.data
current = current.link
end
result << current.data if current
return result
end

inserting in linked lists with ruby

Hi I'm trying to insert a value at a specific index in a linked list in ruby.
Here is my code thus far:
class Node
attr_accessor :data, :pointer, :next
def initialize(data, pointer = nil)
#data = data
#pointer = pointer
end
def next
#data = #pointer
end
end
class LinkedList
attr_accessor :head, :data, :pointer
def initialize(data)
#head = Node.new(data, pointer)
end
def index_at(value_of_index)
current = head
value_of_index.times do
if current.pointer == nil
current = Node.new(nil, nil)
return current = current.data
else
current = current.next
end
end
current.data
end
def insert_at_index(index, value)
current = head
index.times do
current.next
end
current = Node.new(value)
end
end
The problem I've having is with the def insert_at_index method... I can't seem to figure out how to place the new node at the index and value. Any help you can give me would be greatly appreciated.
Say your linked list looks like this:
a -> b -> d -> e
To insert c into the 3rd index, you would move to the second index to get b, create a new node, set b's next to the new node c, and set c's next to the old third index item, d.
This will give you:
a -> b -> c -> d -> e
That said, the code should look like this:
def insert_at_index(index, value)
current = head
# make current b. You may want to put this in a function node_at_index
(index - 1).times do
raise "List not long enough" if current.nil?
current = current.next
end
new_node = Node.new(value) # new node c
new_node.next = current.next # c's next is b's next, d
current.next = new_node # b's next is c
end
From the looks of it there seem to be other issues with your code as well. You're overwriting #data in your next function (you probably meant to just return #pointer), LinkedList#initialize doesn't have pointer defined, etc
You could simplify your Node to look like this:
class Node
attr_accessor :data, :next
def initialize(data, next=nil)
#data = data
#next = next
end
end
Which should work for you.
Here is one solution that worked for me:
class Node
attr_accessor :data, :pointer
alias_method :next, :pointer
def initialize(data, pointer = nil)
#data = data
#pointer = pointer
end
def next
#pointer
end
end
class LinkedList
attr_accessor :head, :data, :pointer
def initialize(data)
#head = Node.new(data, pointer)
end
def index_at(value_of_index)
current = head
value_of_index.times do
if current.pointer == nil
current = Node.new(nil, nil)
return current = current.data
else
current = current.next
end
end
current.data
end
def insert_at_index(index, value)
current = head
(index - 1).times do
if current.pointer != nil
current = current.next
end
end
new_node = Node.new(value)
if current.pointer != nil
new_node.pointer = current.pointer
end
current.pointer = new_node
end
end

Can't break out of simple while loop

I'm writing a search method for my DoublyLinkedList class as such:
def search(val)
current = #head
while current != nil
if current.node_id == val
return current
else
current = current.prev_node
end
end
return nil
end
However when I try to use this search method I seem to be stuck in the while loop.
Here are my DoublyLinkedList and Node classes for reference:
class Node
attr_accessor :node_id, :next_node, :prev_node
def initialize(node_id)
#node_id = node_id
#prev_node = nil
#next_node = nil
end
end
class DoublyLinkedList
attr_accessor :head, :size
def initialize
#size = 0
#head = nil
end
def add(node)
if #head == nil
#head = node
else
node.prev_node = #head
#head.next_node = node
#head = node
end
#size += 1
end
def search(val)
current = #head
while current != nil
if current.node_id == val
return current
break
else
current = current.prev_node
end
end
return nil
end
end
Here's how I'm testing my method:
linked_list = DoublyLinkedList.new
node1 = Node.new '1'
linked_list.add(node1)
puts linked_list.search(node1.node_id)
Sorry if for such verbosity(?) for such a simple question but I just can't see why my while loop won't break - it should return the found node's node_id!
Try break current instead of return current to get out of a loop.

Resources