Advertisement
Guest User

Untitled

a guest
Jan 21st, 2015
226
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.36 KB | None | 0 0
  1. #! usr/bin/env ruby
  2. require './node'
  3.  
  4. # LinkedList implmenetation to be used in polynomial.rb
  5. # Implementation will use head/tail sentinels
  6.  
  7. class LinkedList
  8.  
  9. attr_accessor :head, :tail, :size
  10.  
  11. def initialize
  12. @head = Node.new(0.0, nil, nil)
  13. @tail = Node.new(0.0, nil, nil)
  14. @size = 0
  15.  
  16. @head.set_next(@tail)
  17. @tail.set_prev(@head)
  18. end
  19.  
  20. def add_first(node_to_add)
  21. # Node next should be what was previously the head's next
  22. node_to_add.set_next(@head.next_node)
  23. # Node added should now be previous node of head's former next
  24. @head.next_node.set_prev(node_to_add)
  25. # Next of head should be the node added
  26. @head.set_next(node_to_add)
  27. # Previous node of added node should be the head
  28. node_to_add.set_prev(@head)
  29. end
  30.  
  31. # Similar operation as 'add_first', but implements according to Java's LinkedList add(E e) method.
  32. # The add(E e) method adds an element at the end of the LinkedList.
  33. def add_end(node_to_add)
  34. # Tail's former prev should have it's next set to the node to be added
  35. @tail.prev_node.set_next(node_to_add)
  36. # Tail's previous node now needs to be the previous node of the @tail
  37. node_to_add.set_prev(@tail.prev_node)
  38. # Node that get's added needs to have a next of tail
  39. node_to_add.set_next(@tail)
  40. # Tail's previous node needs to be the node that was added
  41. @tail.set_prev(node_to_add)
  42. end
  43. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement