-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathtwo_stacks.cpp
83 lines (75 loc) · 1.54 KB
/
two_stacks.cpp
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
80
81
82
83
#include <iostream>
using namespace std;
/*
We are given an array,
we need to implement two stacks in it
Reason: cache friendliness
Naive Approach:
Simply divide the array into two parts
assign half of the array to both the stacks
the problem with this is it can lead to wastage of memory
i.e suppose stack1 is full, and stack2 is empty, you still
won't be able to push in stack1
Efficient Approach:
the division will be dynamic, for implementing we will have
two pointers top1 = -1, and top2=n
when I push an item in st1, I will increment top1 ptr
similarly for a push in st2, I will decrement top2 ptr
If they cross each other, stack is overflowing
All operations are O(1)
*/
class TwoStacks{
private:
int *arr;
int top1;
int top2;
int cap;
public:
TwoStacks(int n)
{
cap = n;
top1 = -1;
top2 = cap;
arr = new int[n];
}
void push1(int x)
{
if(top1 < top2-1)
{
++top1;
arr[top1] = x;
}
}
void push2(int x)
{
if(top1 < top2-1)
{
--top2;
arr[top2] = x;
}
else
cout << "\nOverflow!";
}
int pop1()
{
if(top1>=0)
{
int x = arr[top1];
top1--;
return x;
}
else
cout << "\nUnderflow!";
}
int pop2()
{
if(top2<cap)
{
int x = arr[top2];
top2++;
return x;
}
else
cout << "\nUnderflow!";
}
};