Class: RubyDataStructures::StackAsArray

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

Direct Known Subclasses

FifoStack

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(size = 1) ⇒ StackAsArray

Initializes a stack of size size The value of top for an empty stack is nil



6
7
8
9
# File 'lib/RubyDataStructures/stack_as_array.rb', line 6

def initialize(size = 1)
  @length = size
  self.reset
end

Instance Attribute Details

#lengthObject (readonly)

Returns the value of attribute length.



2
3
4
# File 'lib/RubyDataStructures/stack_as_array.rb', line 2

def length
  @length
end

#topObject (readonly)

Returns the value of attribute top.



2
3
4
# File 'lib/RubyDataStructures/stack_as_array.rb', line 2

def top
  @top
end

Instance Method Details

#eachObject



72
73
74
75
76
# File 'lib/RubyDataStructures/stack_as_array.rb', line 72

def each
  @array.each do
    yield
  end
end

#empty?Boolean

Returns true if the stack is empty

Returns:

  • (Boolean)


12
13
14
# File 'lib/RubyDataStructures/stack_as_array.rb', line 12

def empty?
  @top.nil?
end

#firstObject



64
65
66
# File 'lib/RubyDataStructures/stack_as_array.rb', line 64

def first
  @array.first
end

#full?Boolean

Returns true if the stack is full

Returns:

  • (Boolean)


17
18
19
# File 'lib/RubyDataStructures/stack_as_array.rb', line 17

def full?
  @top == @length - 1
end

#lastObject



68
69
70
# File 'lib/RubyDataStructures/stack_as_array.rb', line 68

def last
  @array[@top]
end

#popObject

Pops the stack



40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/RubyDataStructures/stack_as_array.rb', line 40

def pop
  raise "Stack Underflow - The stack is empty" if self.empty?

  x = @array[@top]
  if self.singleton?
    @top = nil
  else
    @top = @top - 1
  end

  return x
end

#push(element) ⇒ Object

Pushes an element element into the stack



26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/RubyDataStructures/stack_as_array.rb', line 26

def push(element)
  
  raise "Stack Overflow - The stack is full" if self.full?

  if self.empty?
    @top = 0
  else
    @top = @top + 1
  end

  @array[@top] = element
end

#resetObject Also known as: reset!

Resets the stack



54
55
56
57
# File 'lib/RubyDataStructures/stack_as_array.rb', line 54

def reset
  @array = Array.new(@length)
  @top = nil
end

#singleton?Boolean

Returns:

  • (Boolean)


21
22
23
# File 'lib/RubyDataStructures/stack_as_array.rb', line 21

def singleton?
  @top == 0
end

#sizeObject



60
61
62
# File 'lib/RubyDataStructures/stack_as_array.rb', line 60

def size
  @array.size
end