-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStackArray.cpp
More file actions
105 lines (77 loc) · 1.39 KB
/
StackArray.cpp
File metadata and controls
105 lines (77 loc) · 1.39 KB
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#include<bits/stdc++.h>
using namespace std;
struct Stack
{
int size;
int top;
int *s;
};
bool isEmpty(struct Stack stk)
{
return stk.top == -1;
}
bool isFull(struct Stack stk)
{
return stk.top == stk.size-1;
}
void push(struct Stack *stk, int x)
{
if(isFull(*stk))
{
printf("Stack Overflow for value %d\n", x);
return;
}
stk->s[++stk->top] = x;
}
int pop(struct Stack *stk)
{
if(isEmpty(*stk))
{
cout << "Stack Underflow\n";
return -1;
}
int x = stk->s[stk->top--];
return x;
}
int top(struct Stack stk)
{
return stk.s[stk.top];
}
int peek(struct Stack stk, int pos)
{
if(isEmpty(stk))
{
printf("No elements in stack\n");
return -1;
}
return stk.s[stk.top - pos + 1];
}
void display(struct Stack stk)
{
printf("Stack : \n");
for(int i=stk.top; i>=0; i--)
{
printf("%d\n", stk.s[i]);
}
}
int main()
{
struct Stack stk;
int n; scanf("%d", &n);
stk.size = n;
stk.s = new int[stk.size];
stk.top = -1;
push(&stk,12);
push(&stk,13);
push(&stk,87);
push(&stk,24);
push(&stk,28);
push(&stk,84);
display(stk);
cout << "Top : " << top(stk) << endl;
pop(&stk);
pop(&stk);
display(stk);
cout << "Top : " << top(stk) << endl;
cout << "Peek at 3 : " << peek(stk,3) << endl;
}