Concepts of Programming Languages

(Sean Pound) #1

502 Chapter 11 Abstract Data Types and Encapsulation Constructs


class StackClass

# Constructor
def initialize
@stackRef = Array.new(100)
@maxLen = 100
@topIndex = -1
end

# push method
def push(number)
if @topIndex == @maxLen
puts "Error in push - stack is full"
else
@topIndex = @topIndex + 1
@stackRef[@topIndex] = number
end
end

# pop method
def pop
if empty
puts "Error in pop - stack is empty"
else
@topIndex = @topIndex - 1
end
end

# top method
def top
if empty
puts "Error in top - stack is empty"
else
@stackRef[@topIndex]
end
end

# empty method
def empty
@topIndex == -1
end
end # of Stack class

# Test code for StackClass
myStack = StackClass.new
myStack.push(42)
Free download pdf