Question: can someone let me know if this ruby code for a double-linked list has the correct syntax with the driver stating the functionality? Because I

can someone let me know if this ruby code for a double-linked list has the correct syntax with the driver stating the functionality? Because I cannot get it to compile

class Node

attr_accessor :value, :prev, :next

def initialize(value)

@value = value

@prev = nil

@next = nil

end

end

class DoublyLinkedList

attr_accessor :head, :tail

def initialize

@head = nil

@tail = nil

end

end

def append(value)

new_node = Node.new(value)

if @tail

@tail.next = new_node

new_node.prev = @tail

@tail = new_node

else

@head = new_node

@tail = new_node

end

end

def prepend(value)

new_node = Node.new(value)

if @head

@head.prev = new_node

new_node.next = @head

@head = new_node

else

@head = new_node

@tail = new_node

end

end

def remove(value)

current_node = @head

while current_node

if current_node.value == value

if current_node.prev

current_node.prev.next = current_node.next

else

@head = current_node.next

end

if current_node.next

current_node.next.prev = current_node.prev

else

@tail = current_node.prev

end

return current_node.value

end

current_node = current_node.next

end

nil

end

def find(value)

current_node = @head

while current_node

if current_node.value == value

return current_node

end

current_node = current_node.next

end

nil

end

def index(value)

current_node = @head

index = 0

while current_node

if current_node.value == value

return index

end

current_node = current_node.next

index += 1

end

nil

end

end

list = DoublyLinkedList.new

list.append(10)

list.append(20)

list.append(30)

list.prepend(5)

list.prepend(3)

list.prepend(1)

puts "List after insertions: #{list.head.value} #{list.head.next.value} #{list.head.next.next.value} #{list.head.next.next.next.value} #{list.head.next.next.next.next.value} #{list.head.next.next.next.next.next.value}"

puts "Value removed: #{list.remove(3)}"

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!