Last active
August 29, 2015 14:09
-
-
Save sotoseattle/5123da60acda8cb98582 to your computer and use it in GitHub Desktop.
Reverse a Linked List (should be refactored)
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
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Also it doesn't take into account freaky cases like size < 3