Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Data Management Databases And Organizations

Authors: Richard T. Watson

3rd Edition

0471418455, 978-0471418450

More Books

Students also viewed these Databases questions

Question

Outline the process of short-selling.

Answered: 1 week ago