Sudo Placement[1.3] | Stack Design
Last Updated :
29 Aug, 2022
Given q number of queries, you need to perform operations on the stack. Queries are of three types 1, 2, and 3. If the operation is to push (1) then push the elements, if the operations are to pop (2) then pop the element and if it is Top (3), then print the element at the top of the stack (If the stack is empty, print “-1”, without quotes).
Examples:
Input: Queries = 6
3
1 5
1 6
1 7
2
3
Output: -1
6
The first query is to print top, but since the stack is empty, so we print -1.
Next three queries are to push 5, 6, and 7, so we pushed them on a stack.
Next query is pop, so we popped 7 from a stack. Final query is to print the
top, so 6 is there at the top and thus printed.
Approach:
Stack can be used to perform the given operation. If the input for a query is 1, then take another input and push the element into the stack using the push() function. If the input for a query is 2, then pop the element using the pop() function in a stack. If the input for a query is 3, then print the top element using the top() function.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
stack< int > s;
void _push( int n)
{
s.push(n);
}
void _pop()
{
s.pop();
}
void print()
{
if (!s.empty())
cout << s.top() << endl;
else
cout << -1 << endl;
}
int main()
{
print();
_push(5);
_push(6);
_push(7);
_pop();
print();
return 0;
}
|
Java
import java.util.*;
class GFG
{
static Stack<Integer> s = new Stack<>();
static void _push( int n)
{
s.push(n);
}
static void _pop()
{
s.pop();
}
static void print()
{
if (!s.empty())
{
System.out.println(s.peek());
}
else
{
System.out.println(- 1 );
}
}
public static void main(String[] args)
{
print();
_push( 5 );
_push( 6 );
_push( 7 );
_pop();
print();
}
}
|
Python3
s = [];
def _push(n):
s.append(n);
def _pop():
s.pop();
def _print():
if ( len (s) > 0 ):
print (s[ len (s) - 1 ]);
else :
print ( "-1" );
if __name__ = = '__main__' :
_print();
_push( 5 );
_push( 6 );
_push( 7 );
_pop();
_print();
|
C#
using System;
using System.Collections.Generic;
class GFG
{
static Stack< int > s = new Stack< int >();
static void _push( int n)
{
s.Push(n);
}
static void _pop()
{
s.Pop();
}
static void print()
{
if (s.Count != 0)
{
Console.WriteLine(s.Peek());
}
else
{
Console.WriteLine(-1);
}
}
public static void Main()
{
print();
_push(5);
_push(6);
_push(7);
_pop();
print();
}
}
|
Javascript
<script>
let s=[];
function _push(n)
{
s.push(n);
}
function _pop()
{
s.pop();
}
function print()
{
if (s.length!=0)
{
document.write(s[s.length-1]+ "<br>" );
}
else
{
document.write(-1+ "<br>" );
}
}
print();
_push(5);
_push(6);
_push(7);
_pop();
print();
</script>
|
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...