K
K
Karina2017-06-19 21:38:22
ruby
Karina, 2017-06-19 21:38:22

Who can help me understand how recursion works in DoubleLinkedList?

It is necessary to write something like DoubleLinkedList. Writing

class DoubleLinkedList

  attr_accessor :head

  # add TO THE END
  def append(new_link)
    if @head == nil
      @head = new_link
      return
    end
    current = @head
    while current.next_link != nil
      current = current.next_link
    end
    current.next_link = new_link
    new_link.prev_link = current
  end

  # print links since tail
  def print_links_at_tail(link = nil)
    if link == nil
      link = @head
      print_links_at_tail(link)
    end
    print_links_at_tail(link.next_link) if link.next_link != nil
    puts link.value
  end
end

class Link

  attr_accessor :value, :next_link, :prev_link

  def initialize(value)
    @value = value
  end
end

struct = DoubleLinkedList.new
link_1 = Link.new('R')
link_2 = Link.new('a')
link_3 = Link.new('i')
link_4 = Link.new('l')
link_5 = Link.new('s')

struct.append(link_1)
struct.append(link_2)
struct.append(link_3)
struct.append(link_4)
struct.append(link_5)
struct.print_links_at_tail


In theory, what should be printed is sliaR. BUT! Printed out - sliaRsliaR. Why?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
longclaps, 2017-06-19
@iKapex

def print_links_at_tail(link = nil)
    if link === nil
      link = @head
      print_links_at_tail(link)
      return # !!!!!!!!!!!!!!!!!!!!!!!!!!!!
    end
    print_links_at_tail(link.next_link) if link.next_link != nil
    puts link.value
  end
end

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question