-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStack_push_pop.cpp
88 lines (80 loc) · 1.86 KB
/
Stack_push_pop.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
85
86
87
88
#include <iostream>
using namespace std;
struct stack
{
int size;
int top;
int *arr;
};
int isEmpty(struct stack *ptr)
{
if (ptr->top == -1)
{
return 1;
}
return 0;
}
int isFull(struct stack *ptr)
{
if (ptr->top == ptr->size-1)
{
return 1;
}
return 0;
}
void push(struct stack * ptr, int value)
{
if (isFull(ptr))
{
cout<<"Stack Overflow! Cannot push "<<value<< " value from the stack"<<endl;
}
else
{
ptr->top++;
ptr->arr[ptr->top] = value;
}
}
int pop(struct stack * ptr)
{
if (isEmpty(ptr))
{
cout<<"Stack Underflow! Cannot pop from the stack"<<endl;
}
else
{
int val = ptr->arr[ptr->top];
ptr->top--;
return val;
}
}
int main ()
{
struct stack *sp = (struct stack *) malloc (sizeof(struct stack));
sp->size = 8;
sp->top = -1;
sp->arr = (int *) malloc (sp->size*sizeof(int));
cout <<"Before pushing, Full : "<<isFull(sp)<<endl;
cout <<"Before pushing, Empty : "<<isEmpty(sp)<<endl;
isFull(sp);
push(sp,1);
push(sp,2);
push(sp,3);
push(sp,4);
push(sp,5);
push(sp,6);
push(sp,7);
push(sp,8);
// push(sp,9); // stack Overflow
cout<<"Poped element : "<<pop(sp)<<endl;
cout<<"Poped element : "<<pop(sp)<<endl;
cout<<"Poped element : "<<pop(sp)<<endl;
cout<<"Poped element : "<<pop(sp)<<endl;
cout<<"Poped element : "<<pop(sp)<<endl;
cout<<"Poped element : "<<pop(sp)<<endl;
cout<<"Poped element : "<<pop(sp)<<endl;
cout<<"Poped element : "<<pop(sp)<<endl;
// cout<<"Poped element : "<<pop(sp)<<endl; // stack Underflow
cout <<"After pushing, Full : "<<isFull(sp)<<endl;
cout <<"After pushing, Empty : "<<isEmpty(sp)<<endl;
return 0;
}