Understanding Java S Stack Class 1686837765
Understanding Java S Stack Class 1686837765
1. public Stack( )
2 public Object pop(): Removes the object at the top of this Stack
and returns that object. Throws an EmptyStackException if Stack
is empty
3 public Object peek(): Returns the object at the top of this stack
without removing it from the Stack. Throws an
EmptyStackException if Stack is empty
Stack specific methods
4 public boolean empty() : Checks whether the Stack is empty or
not.
Output:
10
20
30
Example:
Stack<Integer> numStack =new Stack<Integer>();
numStack.push(10);
numStack.push(20);
numStack.push(30);
while(!numStack.empty())
{
Integer obj= numStack.pop();
System.out.println(obj);
Output:
10
20
30
Example:
Stack<Integer> numStack =new Stack<Integer>();
System.out.println("stack: " + numStack);
numStack.push(10);
numStack.push(20);
numStack.push(30);
System.out.println(“stack:”+ numStack);
System.out.println(“Top element:”+ numStack.peek());
System.out.println(“Popped ele:”+ numStack.pop());
System.out.println("stack: " + numStack);
Output:
stack: [ ]
stack:[10, 20, 30]
Top element:30
Popped ele:30
stack: [10, 20]
Example:
Stack<Integer> numStack =new Stack<Integer>();
System.out.println("stack: " + numStack);
numStack.push(10);
numStack.push(20);
numStack.push(30);
System.out.println("Offset of 10:"+ numStack.search(10));
System.out.println("Offset of 30:"+ numStack.search(30));
System.out.println("Offset of 40:"+ numStack.search(40));
Output:
stack: [ ]
Offset of 10:3
Offset of 30:1
Offset of 40:-1