0% found this document useful (0 votes)
18 views4 pages

Stack Samples

The document demonstrates using a Stack data structure in Java by pushing and popping elements from the stack and printing the stack contents. It shows initializing an empty stack, adding elements to the stack using push(), removing elements using pop(), and checking if the stack is empty.

Uploaded by

ed mac
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views4 pages

Stack Samples

The document demonstrates using a Stack data structure in Java by pushing and popping elements from the stack and printing the stack contents. It shows initializing an empty stack, adding elements to the stack using push(), removing elements using pop(), and checking if the stack is empty.

Uploaded by

ed mac
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 4

 

 public static void main(String args[])


    { OUTPUT:
       
        Stack<Integer> stack = new Stack<Integer>();
   Initial Stack: [10, 15, 30, 20, 5]
       
        stack.push(10);
Popped element: 5
        stack.push(15); Popped element: 20
        stack.push(30);
        stack.push(20);
Stack after pop operation [10, 15, 30]
        stack.push(5);
  
        System.out.println("Initial Stack: " + stack);
  
       
        System.out.println("Popped element: " + stack.pop());
        System.out.println("Popped element: " + stack.pop());
  
       
        System.out.println("Stack after pop operation " + stack);
    }
public class StackExample {
public static void main(String[] args) {
OUTPUT:
Stack<Integer> stack = new Stack<>();

stack.push(1); 6
stack.push(2); 5
stack.push(3); 4
stack.push(4); 3
stack.push(5); 2
stack.push(6); 1

while (!stack.empty()) {
System.out.println(stack.pop());
}
}
}
import java.util.Stack;
public class StackExample2 {
public static void main(String[] args) {

Stack<String> stack = new Stack<>();


System.out.println("new stack is empty: " + stack.empty());
OUTPUT:
stack.push("out");
stack.push("is"); new stack is empty: true
stack.push("class"); peek(): java
stack.push("java"); search for 'java': 1
java class is out
System.out.println("peek(): " + stack.peek());

System.out.println("search for 'java': "+ stack.search("java"));

while (!stack.empty()) {
System.out.print(stack.pop() + " ");
}
}
}

You might also like