Skip to content

Instantly share code, notes, and snippets.

@rummelonp
Created July 4, 2013 09:16
Show Gist options
  • Save rummelonp/5926190 to your computer and use it in GitHub Desktop.
Save rummelonp/5926190 to your computer and use it in GitHub Desktop.
Ruby で単方向リスト的な
class SinglyLinkedList
def initialize
@first_node = nil
end
def add(value)
if last_node = @first_node
while last_node.next_node
last_node = last_node.next_node
end
last_node.next_node = Node.new(value)
else
@first_node = Node.new(value)
end
self
end
alias_method :<<, :add
def length
if node = @first_node
count = 1
while node.next_node
node = node.next_node
count += 1
end
count
else
0
end
end
alias_method :size, :length
def to_s
inspect
end
def inspect
"<SinglyLinkedList: [#{@first_node ? @first_node.inspect : ''}]>"
end
class Node
attr_reader :value
attr_accessor :next_node
def initialize(value)
@value, @next_node = value, nil
end
def to_s
inspect
end
def inspect
if next_node
"#{value.inspect}, #{@next_node.inspect}"
else
value.inspect
end
end
end
end
if $0 == __FILE__
p list = SinglyLinkedList.new
p list.size
p list << 1
p list << 'a'
p list.size
p list << 2
p list << 'b'
p list.size
end
@rummelonp
Copy link
Author

<SinglyLinkedList: []>
0
<SinglyLinkedList: [1]>
<SinglyLinkedList: [1, "a"]>
2
<SinglyLinkedList: [1, "a", 2]>
<SinglyLinkedList: [1, "a", 2, "b"]>
4

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