Skip to content

Instantly share code, notes, and snippets.

@jasonknight
Created July 29, 2019 03:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jasonknight/4bead2baa272a4ade0ab9ac56584fff1 to your computer and use it in GitHub Desktop.
Save jasonknight/4bead2baa272a4ade0ab9ac56584fff1 to your computer and use it in GitHub Desktop.
class Node
attr_accessor :val,:nxt
def initialize(val,nxt)
@val = val
@nxt = nxt
end
end
def print_nodes(head)
while head do
puts head.val
head = head.nxt
end
end
def reverse(head,prev)
if not head.nxt then
head.nxt = prev
return head
end
cnxt = head.nxt
head.nxt = prev
return reverse(cnxt,head)
end
first = Node.new('1',Node.new('2',Node.new('3',Node.new('4',nil))))
first = reverse(first,nil)
print_nodes(first)
@jasonknight
Copy link
Author

Or, the obligatory code golf:

def reverse(head,prev) 
    head.nxt = prev and return head if not head.nxt
    cnxt = head.nxt and head.nxt = prev
    return reverse(cnxt,head)
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment