Advertisement
Guest User

Untitled

a guest
Jul 20th, 2019
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.46 KB | None | 0 0
  1. class LinkedListNode
  2. attr_accessor :value, :next_node
  3.  
  4. def initialize(value, next_node=nil)
  5. @value = value
  6. @next_node = next_node
  7. end
  8. end
  9.  
  10. def print_values(list_node)
  11. print "#{list_node.value} --> "
  12.  
  13. if infinite_list?(list_node)
  14. mu, lam = repetition_params(list_node)
  15. (mu + lam).times do
  16. list_node = list_node.next_node
  17. print "#{list_node.value} --> "
  18. end
  19. print "(and then starts repeating)\n"
  20. else
  21. if list_node.next_node.nil?
  22. print "nil\n"
  23. return
  24. else
  25. print_values(list_node.next_node)
  26. end
  27. end
  28. end
  29.  
  30. def infinite_list?(list_node)
  31. tail = list_node.next_node
  32. head = list_node.next_node.next_node
  33. count = 0
  34. while tail.value != head.value
  35. count += 1
  36. tail = tail.next_node
  37. head = head.next_node.next_node
  38. end
  39.  
  40. mu = 0
  41. tail = list_node
  42. while tail.value != head.value
  43. tail = tail.next_node
  44. head = head.next_node
  45. mu += 1
  46. end
  47.  
  48. lam = 1
  49. head = tail.next_node
  50. while tail.value != head.value
  51. head = head.next_node
  52. lam += 1
  53. end
  54. # puts "mu: #{mu}, #{lam}"
  55. return mu, lam
  56. rescue NoMethodError
  57. false
  58. end
  59. alias :repetition_params :infinite_list?
  60.  
  61. node1 = LinkedListNode.new(37)
  62. node2 = LinkedListNode.new(99, node1)
  63. node3 = LinkedListNode.new(12, node2)
  64. node1.next_node = node3 #creates an infinite loop
  65.  
  66. node4 = LinkedListNode.new(4)
  67. node5 = LinkedListNode.new(5, node4)
  68. node6 = LinkedListNode.new(6, node5)
  69.  
  70.  
  71. print_values(node3)
  72.  
  73. print "-------\n"
  74.  
  75. print_values(node6)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement