Java Reference
In-Depth Information
A NSWERS TO S ELF -T EST Q UESTIONS
1.
public T pop()
{
T top = null ;
if (topNode != null )
{
top = topNode.getData();
topNode = topNode.getNextNode();
} // end if
return top;
} // end pop
2.
No. Although maintaining an external reference to the chain's last node, in addition to the chain's head reference,
would enable you to either access the stack's top entry or push a new entry onto the stack efficiently, it is not
enough to pop the stack. You need a reference to the next-to-last node to remove the chain's last node. To get that
reference, you could either traverse the chain or maintain a reference to the next-to-last node in addition to refer-
ences to the first and last nodes. Thus, placing the stack's top entry at the end of the chain is not as efficient or
easy to implement as placing it at the beginning.
3.
public T pop()
{
T top = peek();
if (!isEmpty()) // or (top != null)
{
stack[topIndex] = null ;
topIndex--;
} // end if
return top;
} // end pop
4.
Change T to the primitive type and do not assign null to stack[topIndex] .
5.
Each push or pop would need to move all of the entries currently in the stack.
6.
The bottom entry. You can then push entries onto the stack without moving the other entries already in the array.
7.
public void clear()
{
for (; topIndex > -1; topIndex--)
stack[topIndex] = null ;
// Assertion: topIndex is -1
} // end clear
8.
public void clear()
{
while (!isEmpty())
pop();
// Assertion: topIndex is -1
} // end clear
9.
No. Since Vector uses an array to store a vector's entries, each push would need to move all of the entries in the
vector to vacate its first location, thus making room for the addition to the stack.
Search WWH ::




Custom Search