Class: DS::Stack
- Inherits:
-
Object
- Object
- DS::Stack
- 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
-
.create(*args) ⇒ Object
Creates stack internally implemented as List.
Instance Method Summary collapse
-
#empty? ⇒ Boolean
If stack is empty returns true otherwise returns false.
-
#initialize(*args) ⇒ Stack
constructor
A new instance of Stack.
-
#peek ⇒ Object
Returns element from the top of the stack.
-
#pop ⇒ Object
Removes element from stack and returns it.
-
#push(x) ⇒ Object
Adds element on the top of the stack.
-
#size ⇒ Object
Returns the stack size.
Constructor Details
#initialize(*args) ⇒ Stack
Returns a new instance of Stack.
5 6 7 8 9 10 11 12 |
# File 'lib/ds/stacks/stack.rb', line 5 def initialize(*args) first = args.first @store = if first.is_a? List first else args || [] end end |
Class Method Details
.create(*args) ⇒ Object
Creates stack internally implemented as List
15 16 17 |
# File 'lib/ds/stacks/stack.rb', line 15 def self.create(*args) new(List.new(*args)) end |
Instance Method Details
#empty? ⇒ Boolean
If stack is empty returns true otherwise returns false.
40 41 42 |
# File 'lib/ds/stacks/stack.rb', line 40 def empty? store.empty? end |
#peek ⇒ Object
Returns element from the top of the stack.
35 36 37 |
# File 'lib/ds/stacks/stack.rb', line 35 def peek store.last end |
#pop ⇒ Object
Removes element from stack and returns it.
25 26 27 |
# File 'lib/ds/stacks/stack.rb', line 25 def pop store.pop unless empty? end |
#push(x) ⇒ Object
Adds element on the top of the stack.
30 31 32 |
# File 'lib/ds/stacks/stack.rb', line 30 def push(x) store.push x end |
#size ⇒ Object
Returns the stack size.
20 21 22 |
# File 'lib/ds/stacks/stack.rb', line 20 def size store.size end |