Class: SinglyLinkedList

Inherits:
Object
  • Object
show all
Defined in:
lib/singly_linked_list.rb

Overview

singly linked list

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeSinglyLinkedList

Returns a new instance of SinglyLinkedList.


5
6
7
# File 'lib/singly_linked_list.rb', line 5

def initialize
  @sentinel = SingleLink.new(nil)
end

Instance Attribute Details

#sentinelObject (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

#popObject


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

#shiftObject


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