Java Reference
In-Depth Information
FIGURE 6-5
An array-based stack after its top entry is removed by
(a) decrementing
topIndex
; (b) setting
stack[topIndex]
to
null
and then decrementing
topIndex
(a)
0
1
2
3
Array
2
topIndex
Returned to client
Top entry of stack
Stack
(b)
0
1
2
3
Array
null
2
topIndex
Returned to client
Top entry of stack
Stack
The following implementation of
pop
reflects these comments:
public
T pop()
{
T top =
null
;
if
(!isEmpty())
{
top = stack[topIndex];
stack[topIndex] =
null
;
topIndex--;
}
// end if
return
top;
}
// end pop
Like
peek
,
pop
is an O(1) operation.
Question 3
Revise the previous implementation of
pop
so that it calls
peek
.
Question 4
If we were to implement a stack of primitives instead of a stack of objects,
what changes should we make to the method
pop
?
6.12
The methods
isEmpty
and
clear
.
The method
isEmpty
involves only
topIndex
:
public boolean
isEmpty()
{