Java Reference
In-Depth Information
Display 15.28
Stack Demonstration Program
1 public class StackExample
2 {
3 public static void main(String[] args)
4 {
5 Stack stack = new Stack( );
6 Stack.push("Billy Rubin");
7 Stack.push("Lou Pole");
8 Stack.push("Polly Ester");
Items come out of the stack in the
reverse order that they were added.
9
while (!stack.isEmpty( ))
10
{
11
String s = stack.pop( );
12
System.out.println(s);
13
}
14
}
15 }
Sample Dialogue
Polly Ester
Lou Pole
Billy Rubin
Self-Test Exercise
17. Display 15.27 does not contain a peek( ) method. Normally this method
would return the data on the top of the stack without popping it off. How
could a user of the Stack class get the same functionally as peek( ) even
though it is not defi ned?
The Queue Data Structure
A stack is a last-in/first-out data structure. Another common data structure is a queue ,
which handles data in a first-in/first-out fashion. A queue is like a line at the bank.
Customers add themselves to the back of the line and are served from the front of the
line. A queue can be implemented with a linked list. However, a queue needs a pointer
at both the head of the list and at the tail (that is, the other end) of the linked list,
because action takes place in both locations. It is easier to remove a node from the head
of a linked list than from the tail of the linked list. So, a simple implementation will
remove nodes from the head of the list (which we will now call the front of the list)
and we will add nodes to the tail end of the list, which we will now call the back of the
list (or the back of the queue).
queue
tail
front
back
 
 
Search WWH ::




Custom Search