1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071 |
- # -*- coding: utf-8 -*-
- # -*- frozen_string_literal: true -*-
- require_relative "single_link_node"
- class SinglyLinkedList
- attr_reader :head
- def initialize value
- @head = new_node value
- end
- def tail
- node = head
- node = node.next until last_node?(node)
- node
- end
- def append value
- tail.next = new_node value
- end
- def prepend value
- new_head = new_node value, head
- self.head = new_head
- end
- def delete value
- return remove_head if head.value == value
- remove_node_with_value value
- end
- def size
- node = head
- count = 1
- until last_node? node
- count += 1
- node = node.next
- end
- count
- end
- private
- attr_writer :head
- def new_node value, next_reference=nil
- SingleLinkNode.new value, next_reference
- end
- def last_node? node
- node.next.nil?
- end
- def remove_head
- old_head_value = head.value
- self.head = head.next
- old_head_value
- end
- def remove_node_with_value value
- node = head
- node = node.next until node.next.value == value
- removed_value = node.next.value
- node.next = node.next.next
- removed_value
- end
- end
|