Using a Stack

//Create the Stack instance and add a couple of elements to it
Stack stack = new Stack();

String s1 = "element 1";
String s2 = "element 2";

stack.push(s1);
stack.push(s2);





Now we have two elements in the stack, and to check what element is at the top of the stack (and will be the first to be removed) we use the peek() method to find out.


System.out.println(stack.peek());


The output is:


element 2


To find out the position of the first element, we use the method search().


//Find position of a certain element
int pos = stack.search("element 1");
System.out.println(pos);


//Code example by www.javadb.com


This will print out the position within the stack.


2


To remove elements from the stack, we use the method pop().


System.out.println(stack.pop());
System.out.println(stack.pop());


This will result in the output:


element 2
element 1


The 'element 2' was added after 'element 1' so that element is removed first.
Now the stack is empty, and to be sure we check with the empty method:


System.out.println(stack.empty());


true

0 comments:

                                                                

Site Meter