Class: Containers::List
- Inherits:
-
Object
- Object
- Containers::List
- Defined in:
- lib/containers/list.rb
Defined Under Namespace
Classes: Node
Class Method Summary collapse
Instance Method Summary collapse
- #empty? ⇒ Boolean
-
#initialize ⇒ List
constructor
A new instance of List.
- #peek_back ⇒ Object
- #peek_front ⇒ Object
- #pop_back ⇒ Object (also: #pop)
- #pop_front ⇒ Object (also: #shift)
- #push_back(element) ⇒ Object (also: #push)
- #push_front(element) ⇒ Object (also: #unshift)
Constructor Details
#initialize ⇒ List
Returns a new instance of List.
4 5 6 7 |
# File 'lib/containers/list.rb', line 4 def initialize @first = nil @last = nil end |
Class Method Details
.[](*arr) ⇒ Object
9 10 11 |
# File 'lib/containers/list.rb', line 9 def self.[](*arr) from_a(arr) end |
.from_a(arr) ⇒ Object
13 14 15 16 17 |
# File 'lib/containers/list.rb', line 13 def self.from_a(arr) l = new arr.each(&l.method(:push_front)) l end |
Instance Method Details
#empty? ⇒ Boolean
19 20 21 |
# File 'lib/containers/list.rb', line 19 def empty? @first == @last && @first.nil? end |
#peek_back ⇒ Object
73 74 75 |
# File 'lib/containers/list.rb', line 73 def peek_back @last&.data end |
#peek_front ⇒ Object
69 70 71 |
# File 'lib/containers/list.rb', line 69 def peek_front @first&.data end |
#pop_back ⇒ Object Also known as: pop
56 57 58 59 60 61 62 63 64 65 66 67 |
# File 'lib/containers/list.rb', line 56 def pop_back to_return = @last&.data unless @last.nil? @last = @last.prev if @last.nil? @first = nil else @last.next = nil unless @last.nil? end end to_return end |
#pop_front ⇒ Object Also known as: shift
33 34 35 36 37 38 39 40 41 42 43 44 |
# File 'lib/containers/list.rb', line 33 def pop_front to_return = @first&.data unless @first.nil? @first = @first.next if @first.nil? @last = nil else @first.prev = nil unless @first.nil? end end to_return end |
#push_back(element) ⇒ Object Also known as: push
46 47 48 49 50 51 52 53 54 |
# File 'lib/containers/list.rb', line 46 def push_back(element) node = Node.new(element, @last, nil) if @last.nil? @first = node else @last.next = node end @last = node end |
#push_front(element) ⇒ Object Also known as: unshift
23 24 25 26 27 28 29 30 31 |
# File 'lib/containers/list.rb', line 23 def push_front(element) node = Node.new(element, nil, @first) if @first.nil? @last = node else @first.prev = node end @first = node end |