2017-10-02 21:56:15 +02:00
|
|
|
# Define a node in the list
|
|
|
|
class Node
|
|
|
|
attr_accessor :value, :next
|
|
|
|
def initialize(value)
|
|
|
|
@value = value
|
|
|
|
@next = nil
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
# A Class for single linked lists (each element links to the next one, but not to the previous one)
|
|
|
|
|
|
|
|
class SingleList
|
2020-10-12 18:59:48 +02:00
|
|
|
include Enumerable
|
2017-10-02 21:56:15 +02:00
|
|
|
attr_accessor :head
|
2020-10-12 18:59:48 +02:00
|
|
|
def initialize
|
2017-10-02 21:56:15 +02:00
|
|
|
@head = nil
|
|
|
|
end
|
|
|
|
|
|
|
|
def insert_tail(value)
|
|
|
|
newNode = Node.new(value)
|
2020-10-12 18:59:48 +02:00
|
|
|
if @head.nil?
|
2017-10-02 21:56:15 +02:00
|
|
|
@head = newNode
|
|
|
|
else
|
|
|
|
tempNode = @head
|
2020-10-12 18:59:48 +02:00
|
|
|
tempNode = tempNode.next until tempNode.next.nil?
|
2017-10-02 21:56:15 +02:00
|
|
|
tempNode.next = newNode
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def insert_head(value)
|
|
|
|
newNode = Node.new(value)
|
2020-10-12 18:59:48 +02:00
|
|
|
if @head.nil?
|
2017-10-02 21:56:15 +02:00
|
|
|
@head = newNode
|
|
|
|
else
|
|
|
|
newNode.next = @head
|
|
|
|
@head = newNode
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
2020-10-12 18:59:48 +02:00
|
|
|
def each
|
|
|
|
return if @head.nil?
|
|
|
|
|
|
|
|
current = @head
|
|
|
|
until current.nil?
|
|
|
|
yield current.value
|
|
|
|
current = current.next
|
2017-10-02 21:56:15 +02:00
|
|
|
end
|
2020-10-12 18:59:48 +02:00
|
|
|
end
|
|
|
|
|
|
|
|
def print_list
|
|
|
|
puts '[' + self.to_a.join(', ') + ']'
|
2017-10-02 21:56:15 +02:00
|
|
|
end
|
|
|
|
|
|
|
|
def delete_head
|
2020-10-12 18:59:48 +02:00
|
|
|
if !@head.nil? && !@head.next.nil?
|
2017-10-02 21:56:15 +02:00
|
|
|
newHead = @head.next
|
|
|
|
@head = newHead
|
2020-10-12 18:59:48 +02:00
|
|
|
elsif !@head.nil? && @head.next.nil?
|
2017-10-02 21:56:15 +02:00
|
|
|
@head = nil
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
def delete_tail
|
2020-10-12 18:59:48 +02:00
|
|
|
return if @head.nil?
|
|
|
|
|
|
|
|
tempNode = @head
|
|
|
|
tempNode = tempNode.next until tempNode.next.next.nil?
|
|
|
|
tempNode.next = nil
|
2017-10-02 21:56:15 +02:00
|
|
|
end
|
|
|
|
|
2020-10-12 18:59:48 +02:00
|
|
|
def empty?
|
|
|
|
@head.nil?
|
2017-10-02 21:56:15 +02:00
|
|
|
end
|
2020-10-12 18:59:48 +02:00
|
|
|
end
|