Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #! usr/bin/env ruby
- require './node'
- # LinkedList implmenetation to be used in polynomial.rb
- # Implementation will use head/tail sentinels
- class LinkedList
- attr_accessor :head, :tail, :size
- def initialize
- @head = Node.new(0.0, nil, nil)
- @tail = Node.new(0.0, nil, nil)
- @size = 0
- @head.set_next(@tail)
- @tail.set_prev(@head)
- end
- def add_first(node_to_add)
- # Node next should be what was previously the head's next
- node_to_add.set_next(@head.next_node)
- # Node added should now be previous node of head's former next
- @head.next_node.set_prev(node_to_add)
- # Next of head should be the node added
- @head.set_next(node_to_add)
- # Previous node of added node should be the head
- node_to_add.set_prev(@head)
- end
- # Similar operation as 'add_first', but implements according to Java's LinkedList add(E e) method.
- # The add(E e) method adds an element at the end of the LinkedList.
- def add_end(node_to_add)
- # Tail's former prev should have it's next set to the node to be added
- @tail.prev_node.set_next(node_to_add)
- # Tail's previous node now needs to be the previous node of the @tail
- node_to_add.set_prev(@tail.prev_node)
- # Node that get's added needs to have a next of tail
- node_to_add.set_next(@tail)
- # Tail's previous node needs to be the node that was added
- @tail.set_prev(node_to_add)
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement