Java Reference
In-Depth Information
Finally, we can now run the same demonstration program as for arrays. The
result is identical since the
semantic
of the methods declared in the stack
interface is the same. We get the following Java program:
Program 8.19
Demonstration program: Stacks using linked lists
class
DemoStackList
{
public static void
main( String
[ ]
args )
{
Stack myStack=
new
Stack () ;
int
i;
for
(i=0;i
<
10; i++)
myStack.Push(i);
for
(i=0;i
<
15; i++)
System . out . println (myStack . Pull () ) ;
}
}
In summary, objects provide a nice framework for encapsulating data. The
methods acting on object are non-static functions that can access the fields of
the current object. Thus methods can be interpreted as basic algorithms on
structured data.
8.7 Exercises
Exercise 8.1 (Stacks of strings)
Implement a stack for storing strings. Write static functions
push
and
pop
. Then provide the equivalent methods for that class, and discuss the
advantages of using object methods.
Exercise 8.2 (Flood-filling binary images using stacks and queues)
Consider a binary image defined by a bi-dimensional array of booleans:
boolean [] [] image;
. Provide a function
drawRectangle
that draws
the border of a rectangle given by its bottom left corner and with/height
dimensions. Create a binary image by drawing at random
n
rectangle
borders using the function
Math.random()
. We would like to perform
the flood-filling at image pixel (
x, y
). Implement the recursive function
FloodFillingStack
by using a pixel stack. Similarly, implement the
Search WWH ::
Custom Search