This repository has been archived by the owner on Nov 14, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 577
/
k-stacks.cpp
84 lines (67 loc) · 1.56 KB
/
k-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
84
#include <bits/stdc++.h>
using namespace std;
struct kStacks
{
int *arr;
int *top;
int *next;
int cap, k;
int freeTop;
kStacks(int k1, int n){
k = k1; cap = n;
arr = new int[cap];
top = new int[k];
next = new int[cap];
for (int i = 0; i < k; i++)
top[i] = -1;
freeTop = 0;
for (int i=0; i<cap-1; i++)
next[i] = i+1;
next[cap-1] = -1;
}
bool isFull() { return (freeTop == -1); }
bool isEmpty(int sn) { return (top[sn] == -1); }
void push(int x, int sn)
{
if (isFull())
{
cout << "\nStack Overflow\n";
return;
}
int i = freeTop;
freeTop = next[i];
next[i] = top[sn];
top[sn] = i;
arr[i] = x;
}
int pop(int sn)
{
if (isEmpty(sn))
{
cout << "\nStack Underflow\n";
return INT_MAX;
}
int i = top[sn];
top[sn] = next[i];
next[i] = freeTop;
freeTop = i;
return arr[i];
}
};
int main()
{
int k = 3, n = 10;
kStacks ks(k, n);
ks.push(15, 2);
ks.push(45, 2);
ks.push(17, 1);
ks.push(49, 1);
ks.push(39, 1);
ks.push(11, 0);
ks.push(9, 0);
ks.push(7, 0);
cout << "Popped element from stack 2 is " << ks.pop(2) << endl;
cout << "Popped element from stack 1 is " << ks.pop(1) << endl;
cout << "Popped element from stack 0 is " << ks.pop(0) << endl;
return 0;
}