singly_linked_list.rb 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. # -*- coding: utf-8 -*-
  2. # -*- frozen_string_literal: true -*-
  3. require_relative "single_link_node"
  4. class SinglyLinkedList
  5. attr_reader :head
  6. def initialize value
  7. @head = new_node value
  8. end
  9. def tail
  10. node = head
  11. node = node.next until last_node?(node)
  12. node
  13. end
  14. def append value
  15. tail.next = new_node value
  16. end
  17. def prepend value
  18. new_head = new_node value, head
  19. self.head = new_head
  20. end
  21. def delete value
  22. return remove_head if head.value == value
  23. remove_node_with_value value
  24. end
  25. def size
  26. node = head
  27. count = 1
  28. until last_node? node
  29. count += 1
  30. node = node.next
  31. end
  32. count
  33. end
  34. private
  35. attr_writer :head
  36. def new_node value, next_reference=nil
  37. SingleLinkNode.new value, next_reference
  38. end
  39. def last_node? node
  40. node.next.nil?
  41. end
  42. def remove_head
  43. old_head_value = head.value
  44. self.head = head.next
  45. old_head_value
  46. end
  47. def remove_node_with_value value
  48. node = head
  49. node = node.next until node.next.value == value
  50. removed_value = node.next.value
  51. node.next = node.next.next
  52. removed_value
  53. end
  54. end