Skip to content

Instantly share code, notes, and snippets.

@AlexAvlonitis
Last active January 24, 2022 18:41
Show Gist options
  • Save AlexAvlonitis/880a135e5e108b410a34cc9386266107 to your computer and use it in GitHub Desktop.
Save AlexAvlonitis/880a135e5e108b410a34cc9386266107 to your computer and use it in GitHub Desktop.
Reverse array and linked list recursively in ruby
# Reverse array recursively
def reverse_array(arr)
return arr if arr.empty?
reverse_array(arr[1..-1]) + [arr.first]
end
p reverse_array([1, 2, 3])
# Reverse singly linked list
class LinkedList
attr_accessor :head
def initialize(head = nil)
@head = head
end
def print
c = head
while c
puts c.value
c = c.next
end
end
end
class Node
attr_accessor :next, :value
def initialize(value = nil)
@value = value
@next = nil
end
end
linked_list = LinkedList.new(Node.new(1))
linked_list.head.next = Node.new(2)
linked_list.head.next.next = Node.new(3)
linked_list.print
def reverse_linked_list(node)
return node if node.next.nil?
n = reverse_linked_list(node.next)
node.next.next = node
node.next = nil
n
end
linked_list.head = reverse_linked_list(linked_list.head)
linked_list.print
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment