Class: SingleLinkedList
- Inherits:
-
Object
- Object
- SingleLinkedList
- Defined in:
- lib/singly_linked_list.rb
Overview
singly linked list
Instance Attribute Summary collapse
-
#sentinel ⇒ Object
readonly
Returns the value of attribute sentinel.
Instance Method Summary collapse
-
#initialize ⇒ SingleLinkedList
constructor
A new instance of SingleLinkedList.
- #pop ⇒ Object
- #push(val) ⇒ Object
- #shift ⇒ Object
- #unshift(val) ⇒ Object
Constructor Details
#initialize ⇒ SingleLinkedList
5 6 7 |
# File 'lib/singly_linked_list.rb', line 5 def initialize @sentinel = SingleLink.new(nil) end |
Instance Attribute Details
#sentinel ⇒ Object (readonly)
Returns the value of attribute sentinel.
3 4 5 |
# File 'lib/singly_linked_list.rb', line 3 def sentinel @sentinel end |
Instance Method Details
#pop ⇒ Object
9 10 11 12 13 14 15 |
# File 'lib/singly_linked_list.rb', line 9 def pop prev, last = walkthrough raise "cannot pop from empty list" if prev.nil? prev.next = nil last.val end |
#push(val) ⇒ Object
17 18 19 20 21 22 23 |
# File 'lib/singly_linked_list.rb', line 17 def push(val) link = SingleLink.new(val) _, last_link = walkthrough last_link.next = link self end |
#shift ⇒ Object
25 26 27 28 29 30 31 32 |
# File 'lib/singly_linked_list.rb', line 25 def shift first_link = @sentinel.next raise "cannot shift from empty list" if first_link.nil? val = first_link.val @sentinel.next = first_link.next val end |
#unshift(val) ⇒ Object
34 35 36 37 38 39 |
# File 'lib/singly_linked_list.rb', line 34 def unshift(val) link = SingleLink.new(val) @sentinel.next, link.next = link, @sentinel.next self end |