Stack Operations | Practice | GeeksforGeeks

This Java module deals with Stacks, Queues, and ArrayLists. We'll perform various operations on them.
Given a stack of integers and Q queries. The task is to perform operation on stack according to the query.
Note: use push() to add element in the stack, peek() to get topmost element without removal, pop() gives topmost element with removal, search() to return position if found else -1.
Input Format:
First line of input contains nubmer of testcases T. For each testcase, first line of input contains Q, number of queries. Next line contains Q queries seperated by space. Queries are as:


i x : (adds element x in the stack).


r : (returns and removes the topmost element from the stack).


h : Prints the topmost element.


f y : (check if the element y is present or not in the stack). Print "Yes" if present, else "No".



i x : (adds element x in the stack).

i x : (adds element x in the stack).

r : (returns and removes the topmost element from the stack).

r : (returns and removes the topmost element from the stack).

h : Prints the topmost element.

h : Prints the topmost element.

f y : (check if the element y is present or not in the stack). Print "Yes" if present, else "No".

f y : (check if the element y is present or not in the stack). Print "Yes" if present, else "No".
Output Format:
For each testcase, perform Q queries and print the output wherever required.
Your Task:
Your task is to complete functions insert(), remove(), headOf_Stack() and find(), to insert, remove returning top element and findiing the elment in stack respectively.
Constraints:
1 <= T <= 100
1 <= Q <= 103
Example:
Input:
2
6
i 2 i 4 i 3 i 5 h f 8
4
i 3 i 4 r f 3
Output:
5
No
Yes
Explanation:
Testcase 1: Inserting 2, 4, 3, and 5 onto the stack. Returning top element which is 5. Finding 8 will give No, as 8 is not in the stack.
0
rahul8781 month ago
--------------------JAVA-SOLUTION------------------------
class Geeks
{
    // Function to insert element to stack
    public static void insert(Stack<Integer> st, int x)
    {
        st.push(x);
        
    }
    
    // Function to pop element from stack
    public static void remove(Stack<Integer> st)
    {
        int x = st.pop();
        
    }
    
    // Function to return top of stack
    public static void headOf_Stack(Stack<Integer> st)
    {
        int x = st.peek();
        System.out.println(x + " ");
    }
    
    // Function to find the element in stack
    public static void find(Stack<Integer> st, int val)
    {
    
        if(st.contains(val)){
            System.out.println("Yes");
        }
        else{
            System.out.println("No");
        }
        
    }
}
0
emmanueluluabuike3 months ago
Simple Java Solution
// Function to insert element to stack
    public static void insert(Stack<Integer> st, int x)
    {
        // Your code here
        st.push(x);
    }
    
    // Function to pop element from stack
    I changed this from void to int
    public static int remove(Stack<Integer> st)
    {
        int x = st.pop();// Your code here
        return x;
    }
    
    // Function to return top of stack
    public static void headOf_Stack(Stack<Integer> st)
    {
        int x = st.peek();// Your code here
        System.out.println(x + " ");
    }
    
    // Function to find the element in stack
    public static void find(Stack<Integer> st, int val)
    {
        if(st.contains(val)){
            System.out.println("Yes");
        }
        else{
            System.out.println("No");
        }
        
    }
0
feyza3 months ago
class Geeks{   // Function to insert element to stack   public static void insert(Stack<Integer> st, int x)   {       st.push(x);          }      // Function to pop element from stack   public static void remove(Stack<Integer> st)   {       st.pop();          }      // Function to return top of stack   public static void headOf_Stack(Stack<Integer> st)   {        int x = st.peek();       System.out.println(x + " ");   }      // Function to find the element in stack   public static void find(Stack<Integer> st, int val)   {          if(st.contains(val)){           System.out.println("Yes");       }       else{           System.out.println("No");       }          }}
+1
o36csbhch5stx2bnu7nqk1lty2talmptprfody7l4 months ago
#Python code for this problem#
#DM on insta for queries#
0_tausif_raza_0  ← iD
 
class Stack():
    def __init__(self):
        self.items=[]
                     
    def isEmp(self):
        if self.items==[]:
            return True
        else:
            return False
 
    def push(self,data):
        self.items.append(data)
   
    def Spop(self):
        x=len(self.items)
        po=self.items.pop(x-1)
        print('po',po)
 
    def show(self):
        print(self.items)
 
    def search(self,data):
        if data in self.items:
            return "Yes"
        else:
            return "No"
 
s1=Stack()
# all the operations performed manually
#you can delete this part and add a menu or add your own commands
 
s1.push("hi")
s1.push(2)
s1.push(3)
s1.push(4)
s1.show()
print(s1.search(10))
print(s1.search(3))
s1.isEmp()      
-1
ja90806 months ago
class Geeks{   // Function to insert element to stack   public static void insert(Stack<Integer> st, int x)   {       st.push(x);          }      // Function to pop element from stack   public static void remove(Stack<Integer> st)   {       st.pop();                        }      // Function to return top of stack   public static void headOf_Stack(Stack<Integer> st)   {       int x = st.peek();       System.out.println(x + " ");   }      // Function to find the element in stack   public static void find(Stack<Integer> st, int val)   {       int a =0;       Stack<Integer> temp = new Stack<Integer>();       while(!st.empty()){           if(st.peek()==val){               a=1;               break;           }           temp.push(st.peek());           st.pop();       }       while(!temp.empty()){           st.push(temp.peek());           temp.pop();       }                 if(a==1){           System.out.println("Yes");       }       else{           System.out.println("No");       }          }} 
0
shubhmish2236 months ago
// { Driver Code Starts
//Initial Template for Java
import java.util.*;


 // } Driver Code Ends
//User function Template for Java

// Helper class to implement functions
// insert : to insert element to stack
// remove : to pop element from stack
// headOf_Stack : to return top of stack
// find : to find the element in stack
class Geeks
{
    // Function to insert element to stack
    public static void insert(Stack<Integer> st, int x)
    {
        st.push(x);// Your code here
        
    }
    
    // Function to pop element from stack
    public static void remove(Stack<Integer> st)
    {
        st.pop() ;// Your code here
        
    }
    
    // Function to return top of stack
    public static void headOf_Stack(Stack<Integer> st)
    {
        int x =Integer()st.peek() // Your code here
        System.out.println(x + " ");
    }
    
    // Function to find the element in stack
    public static void find(Stack<Integer> st, int val)
    {
    
        if(st.search(val)!=-1){
            System.out.println("Yes");
        }
        else{
            System.out.println("No");
        }
        
    }
}


// { Driver Code Starts.

// Driver class with Driver code
class GFG 
{
	// Driver code
	public static void main (String[] args) 
	{
		Scanner sc = new Scanner(System.in);
		int t = sc.nextInt();
		
		while(t-- > 0)
		{
		    // Declaring stack of integers
		    Stack <Integer> st = new Stack<Integer>();
		    
		    int q = sc.nextInt();
		    
		    // Working with queries
		    while(q-- > 0)
		    {
		        char ch = sc.next().charAt(0);
		        Geeks obj = new Geeks();
		       if(ch == 'i')
		      {
		         int x = sc.nextInt();
		         obj.insert(st, x);
		      }
		    
		      if(ch == 'r')
		      {
		          obj.remove(st);
		      }
		      
		      if(ch == 'h')
		      {
		          obj.headOf_Stack(st);
		      }
		      if(ch == 'f')
		      {
		          int x = sc.nextInt();
		          obj.find(st, x);
		      }
		      
		      
		    }
		    // System.out.println();
		 }
	}
}  // } Driver Code Ends
-12
vtu179137 months ago
0
Mukund Sadani11 months ago
Mukund Sadani
Correct Answer.Correct AnswerExecution Time:0.35
class Geeks{    // Function to insert element to stack    public static void insert(Stack<integer> st, int x)    {        // Your code here        st.push(x);
    }
    // Function to pop element from stack    public static void remove(Stack<integer> st)    {        if(!st.isEmpty()){        int x = st.pop();        }
    }
    // Function to return top of stack    public static void headOf_Stack(Stack<integer> st)    {        if(!st.isEmpty()){        int x = st.peek();        System.out.println(x + " ");        }    }
    // Function to find the element in stack    public static void find(Stack<integer> st, int val)    {
        if(st.search(val)>0){            System.out.println("Yes");        }        else{            System.out.println("No");        }
    }}
0
Debojyoti Sinha1 year ago
Debojyoti Sinha
Correct Answer.Correct AnswerExecution Time:0.47
class Geeks{    public static void insert(Stack<integer> st, int x)    {        st.push(x);    }        public static void remove(Stack<integer> st)    {        int x = st.pop();            }        public static void headOf_Stack(Stack<integer> st)    {        int x = st.peek();                System.out.println(x + " ");    }        public static void find(Stack<integer> st, int val)    {            if(st.contains(val))        {            System.out.println("Yes");        }        else        {            System.out.println("No");        }    }}
0
Amir Ansari1 year ago
Amir Ansari
Correct AnswerExecution Time:0.37class Geeks{    // Function to insert element to stack    public static void insert(Stack<integer> st, int x)    {        // Your code here        st.push(x);
    }
    // Function to pop element from stack    public static void remove(Stack<integer> st)    {         if(!st.isEmpty()){           int x = st.pop();// Your code here           }
    }
    // Function to return top of stack    public static void headOf_Stack(Stack<integer> st)    {        if(!st.isEmpty()){        int x = st.peek();// Your code here        System.out.println(x + " ");        }    }
    // Function to find the element in stack    public static void find(Stack<integer> st, int val)    {
       if(st.search(val)> 0){            System.out.println("Yes");        }        else{            System.out.println("No");        }
    }}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.