Java Reference
In-Depth Information
ids: 10,20,30
After ids.unshift(100, 200, 300): 100,200,300,10,20,30
After ids.shift(): 200,300,10,20,30
After ids.push(1, 2, 3): 200,300,10,20,30,1,2,3
After ids.pop(): 200,300,10,20,30,1,2
Using these methods, you can implement a stack, a queue, and a doubly-ended
queue. Let us implement a stack using the
push()
and
pop()
methods. Listing 7-2
contains the code for the
Stack
object. It holds the stack's data in a private
Array
object.
It provides
isEmpty()
,
push()
,
pop()
, and
peek()
methods to perform stack operations. It
override the
toString()
method of the
Object.prototype
to return the current elements
in the stack as a string. Listing 7-3 contains the code to test the
Stack
object.
Listing 7-2.
A Stack Object Declaration
// stack.js
// Define the constructor for the Stack object
function Stack(/*varargs*/) {
// Define a private array to keep the stack elements
var data = new Array();
// If any arguments were passed to the constructor, add them to the stack
for (var i in arguments) {
data.push(arguments[i]);
}
// Define methods
this.isEmpty = function () {
return (data.length === 0);
};
this.pop = function () {
if (this.isEmpty()) {
throw new Error("Stack is empty.");
}
return data.pop();
};
this.push = function (arg) {
data.push(arg);
return arg;
};
Search WWH ::
Custom Search