Class: LinkedList
- Inherits:
-
Object
- Object
- LinkedList
- Defined in:
- lib/doubly_linked_list.rb
Overview
doubly linked list
Instance Attribute Summary collapse
-
#begin_sentinel ⇒ Object
readonly
Returns the value of attribute begin_sentinel.
-
#last_sentinel ⇒ Object
readonly
Returns the value of attribute last_sentinel.
Instance Method Summary collapse
-
#initialize ⇒ LinkedList
constructor
A new instance of LinkedList.
- #pop ⇒ Object
- #push(val) ⇒ Object
- #shift ⇒ Object
- #unshift(val) ⇒ Object
Constructor Details
#initialize ⇒ LinkedList
Returns a new instance of LinkedList.
5 6 7 8 |
# File 'lib/doubly_linked_list.rb', line 5 def initialize @begin_sentinel = Link.new(nil) @last_sentinel = Link.new(nil) end |
Instance Attribute Details
#begin_sentinel ⇒ Object (readonly)
Returns the value of attribute begin_sentinel.
3 4 5 |
# File 'lib/doubly_linked_list.rb', line 3 def begin_sentinel @begin_sentinel end |
#last_sentinel ⇒ Object (readonly)
Returns the value of attribute last_sentinel.
3 4 5 |
# File 'lib/doubly_linked_list.rb', line 3 def last_sentinel @last_sentinel end |
Instance Method Details
#pop ⇒ Object
10 11 12 13 14 15 16 17 18 |
# File 'lib/doubly_linked_list.rb', line 10 def pop last_link = @last_sentinel.prev return nil if last_link == @begin_sentinel last_link.prev.next = @last_sentinel @last_sentinel.prev = last_link.prev last_link.val end |
#push(val) ⇒ Object
20 21 22 23 24 25 26 27 28 29 30 31 |
# File 'lib/doubly_linked_list.rb', line 20 def push(val) link = Link.new(val) last_link = @last_sentinel.prev unless last_link.nil? last_link.next, link.prev = link, @last_sentinel.prev else @begin_sentinel.next = link end @last_sentinel.prev = link self end |
#shift ⇒ Object
46 47 48 49 50 51 52 53 54 |
# File 'lib/doubly_linked_list.rb', line 46 def shift first_link = @begin_sentinel.next return nil if first_link.nil? @begin_sentinel.next = first_link.next first_link.next.prev = @begin_sentinel first_link.val end |
#unshift(val) ⇒ Object
33 34 35 36 37 38 39 40 41 42 43 44 |
# File 'lib/doubly_linked_list.rb', line 33 def unshift(val) link = Link.new(val) first_link = @begin_sentinel.next unless first_link.nil? first_link.prev, link.next = link, first_link else @last_sentinel.prev = link end @begin_sentinel.next = link self end |