-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathImplement stack using array
79 lines (68 loc) · 1.93 KB
/
Implement stack using array
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
Implement a Stack using Array. Your task is to complete the functions below.
Input Format:
The first line of the input contains an integer 'T' denoting the number of test cases. Then T test cases follow.
First line of each test case contains an integer Q denoting the number of queries .
A Query Q is of 2 Types:
(i) 1 x (a query of this type means pushing 'x' into the stack)
(ii) 2 (a query of this type means to pop element from stack and print the poped element)
The second line of each test case contains Q queries seperated by space.
Output Format:
The output for each test case will be space separated integers having -1 if the stack is empty else the element poped out from the stack .
Your Task:
You are required to complete two methods push which take one argument an integer 'x' to be pushed into the stack and pop which returns a integer poped out from the stack.
Constraints:
1 <= T <= 100
1 <= Q <= 100
1 <= x <= 100
Example:
Input:
1
5
1 2 1 3 2 1 4 2
4
2 1 4 1 5 2
Output:
3 4
-1 5
Explanation:
In the first test case for query
1 2 the stack will be {2}
1 3 the stack will be {2 3}
2 poped element will be 3 the stack will be {2}
1 4 the stack will be {2 4}
2 poped element will be 4
CODE:
/*Please note that it's Function problem i.e.
you need to write your solution in the form of Function(s) only.
Driver Code to call/invoke your function is mentioned above.*/
/*
The structure of the class is
class Stack_using_array {
int top;
int arr[]=new int[1000];
Stack_using_array()
{
top = -1;
}
*/
class GfG
{
/* The method push to push element into the stack */
void push(int a, Stack_using_array ob)
{
//Your code
if(ob.top<1000){
ob.top++;
ob.arr[ob.top]=a;}
}
/*The method pop which return the element poped out of the stack*/
int pop(Stack_using_array ob)
{
//Your code
int x=-1;
if(ob.top!=-1){
x=ob.arr[ob.top];
ob.top--;}
return x;
}
}