Java Reference
In-Depth Information
-
Pull
(or
Pop
): Remove the last inserted element from the stack.
These two basic methods of stacks can be implemented using various schemes.
We describe two of them to insist on the notion of abstract data-structures:
Arrays and linked lists.
8.6.1 Stack interface and an array implementation
We may implement a stack using an array. The array is declared as an object
field with an index variable that indicates the position of the last inserted
element: the top of the stack. The
Push
/
Pull
primitives of the
stack interface
are then implemented as follows:
Program 8.15
Stack implementation using an array
class
StackArray
int
nbmax ;
int
index ;
int
[
] array ;
// Constructors
StackArray(
int
n)
this
. nbmax=n ;
array=
new i n t
[ nbmax ] ;
1;
System . out . println (
"Succesfully created a stack array object
..."
);
index =
−
}
// Methods
void
Push(
int
element)
if
(index
<
nbmax
−
1)
array[++index]=element ;
}
int
Pull ()
if
(index
>
=0 )
return
array [ index
−−
];
else return
−
1;
}
}
Let us store the above
StackArray
class into a corresponding Java source code
text file:
StackArray.java
. Then compile this code for manipulating stacks
using arrays:
prompt% javac StackArray.java
Search WWH ::
Custom Search