Class: DS::Stack

Inherits:
Object
  • Object
show all
Defined in:
lib/ds/stacks/stack.rb

Overview

Class implements Stack data structure. Internaly uses array or linked list to store elements.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ Stack

Returns a new instance of Stack.



5
6
7
8
9
10
11
# File 'lib/ds/stacks/stack.rb', line 5

def initialize(*args)
  @store = if args.first.is_a? List
             args.first
           else
             args || []
           end
end

Class Method Details

.create(*args) ⇒ Object

Creates stack internally implemented as List



14
15
16
# File 'lib/ds/stacks/stack.rb', line 14

def self.create(*args)
  new(List.new(*args))
end

Instance Method Details

#empty?Boolean

If stack is empty returns true otherwise returns false.

Returns:

  • (Boolean)


39
40
41
# File 'lib/ds/stacks/stack.rb', line 39

def empty?
  store.empty?
end

#peekObject

Returns element from the top of the stack.



34
35
36
# File 'lib/ds/stacks/stack.rb', line 34

def peek
  store.last
end

#popObject

Removes element from stack and returns it.



24
25
26
# File 'lib/ds/stacks/stack.rb', line 24

def pop
  store.pop unless empty?
end

#push(x) ⇒ Object

Adds element on the top of the stack.



29
30
31
# File 'lib/ds/stacks/stack.rb', line 29

def push(x)
  store.push x
end

#sizeObject

Returns the stack size.



19
20
21
# File 'lib/ds/stacks/stack.rb', line 19

def size
  store.size
end