Class: LinkedList

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

Overview

doubly linked list

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeLinkedList

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_sentinelObject (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_sentinelObject (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

#popObject


10
11
12
13
14
15
16
# File 'lib/doubly_linked_list.rb', line 10

def pop
  last_link = @last_sentinel.prev
  val = last_link.val
  @last_sentinel.prev = last_link.prev

  val
end

#push(val) ⇒ Object


18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/doubly_linked_list.rb', line 18

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

#shiftObject


44
45
46
47
48
49
50
# File 'lib/doubly_linked_list.rb', line 44

def shift
  first_link = @begin_sentinel.next
  return nil if first_link.nil?
  @begin_sentinel.next = first_link.next

  first_link.val
end

#unshift(val) ⇒ Object


31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/doubly_linked_list.rb', line 31

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