Array in Ruby already has built in push and pop function you can use, but if you want to make it more strict and idiot proof, here's how you can implement it.
class Stack
def initialize
@stack = []
end
def push(x)
@stack.push(x)
end
def pop
@stack.pop unless is_empty?
end
def peek
@stack.last
end
def is_empty?
@stack.empty?
end
end
class Queue
def initialize
@queue = []
end
def enqueue(x)
@queue << x
end
def dequeue(x)
@queue.shift
end
def peek
@queue.first
end
def is_empty?
@queue.empty?
end
end
J
Tuesday, September 23, 2008
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment