Last active
January 24, 2022 18:41
-
-
Save AlexAvlonitis/880a135e5e108b410a34cc9386266107 to your computer and use it in GitHub Desktop.
Reverse array and linked list recursively in ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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