Skip to content

Instantly share code, notes, and snippets.

@sotoseattle
Last active August 29, 2015 14:09
Show Gist options
  • Save sotoseattle/5123da60acda8cb98582 to your computer and use it in GitHub Desktop.
Save sotoseattle/5123da60acda8cb98582 to your computer and use it in GitHub Desktop.
Reverse a Linked List (should be refactored)
class Node
attr_accessor :val, :next
def initialize(val)
@val = val
@next = nil
end
end
class List
attr_accessor :head
def initialize
@head = nil
self
end
def push(val)
n = Node.new(val)
n.next = @head
@head = n
self
end
def to_s
s = []
n = @head
while n
s << n.val
n = n.next
end
s.join(', ')
end
def reverse
p, n, x = @head, @head.next, @head.next.next
while x
n.next = p
p.next = nil if p == @head
p, n, x = n, x, x.next
n.next = p unless x
end
@head = n
end
end
l = List.new.push(0).push(1).push(2).push(3).push(4).push(5)
puts l
puts l.head.val
l.reverse
puts '------'
puts l
puts l.head.val
@sotoseattle
Copy link
Author

Also it doesn't take into account freaky cases like size < 3

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