stack.rb 672 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. # -*- coding: utf-8 -*-
  2. # -*- frozen_string_literal: true -*-
  3. require_relative "./singly_linked_list"
  4. class StackOverflow < StandardError; end
  5. class Stack
  6. attr_reader :capacity
  7. def initialize capacity
  8. @capacity = capacity
  9. @list = new_list nil
  10. end
  11. def push element
  12. raise StackOverflow if size >= capacity
  13. list.prepend element
  14. end
  15. def size
  16. list.size - 1
  17. end
  18. def empty?
  19. size.zero?
  20. end
  21. def top
  22. list.head.value
  23. end
  24. def pop
  25. unless empty?
  26. popped = list.head.value
  27. list.delete popped
  28. end
  29. popped
  30. end
  31. private
  32. attr_reader :list
  33. def new_list value
  34. SinglyLinkedList.new value
  35. end
  36. end