-
Notifications
You must be signed in to change notification settings - Fork 0
/
stackdsa.c
132 lines (124 loc) · 2.31 KB
/
stackdsa.c
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
#include<stdio.h>
struct arraystack
{
int top;
int capacity;
int *array;
};
struct arraystack* createstack(int);
struct arraystack* createstack(int cap)
{
struct arraystack* stack;
stack=(struct arraystack*)malloc(sizeof(struct arraystack)); //it returns the void pointer that would be typecast into arraysrack
stack->top=-1;
stack->capacity=cap;
stack->array=malloc(sizeof(int)*stack->capacity);
return stack;
}
int isfull(struct arraystack* stack)
{
int cap;
// cap=stack->capacity;
if(stack->top==(stack->capacity)-1)
return(1);
else
return(0);
}
int isempty(struct arraystack* stack)
{
if(stack->top==-1)
return(1);
else
return(0);
}
void push(struct arraystack* stack,int item)
{
if(!isfull(stack))
{
stack->top++;
stack->array[stack->top]=item;
}
}
int pop(struct arraystack* stack )
{
int item;
if(!isempty(stack))
{
item=stack->array[stack->top];
stack->top--;
return item;
}
return -1;
}
int peek(struct arraystack *stack)
{
int n;
if(stack->top==-1)
return -1;
else
n=stack->array[stack->top];
return n;
}
void traverse(struct arraystack *stack)
{
int i;
if(stack->top==-1)
printf("Stack is empty!!\n");
else
printf("Stack elements are:\n");
for(i=0;i<=stack->top;i++)
{
printf("%d\n",stack->array[i]);
}
}
void main()
{
int n,item;
struct arraystack* stack;
stack=createstack(2);
printf("\t\t\t 1. Push operation\n");
printf("\t\t\t 2. Pop operation\n");
printf("\t\t\t 3. Traverse operation\n");
printf("\t\t\t 4. Peek operation\n");
printf("\t\t\t 5. Exit\n");
while(1)
{
printf("Enter your choice: ");
scanf("%d",&n);
switch(n)
{
case 1:
if(isfull(stack))
printf("Stack is overflow!!\n");
else
{
printf("Enter data: ");
scanf("%d",&item);
push(stack,item);
}
break;
case 2:
item=pop(stack);
if(item==-1)
printf("Stack is underflow!!\n");
else
{
printf("Poped element: %d \n",item);
}
break;
case 3:
traverse(stack);
break;
case 4:
item=peek(stack);
if(item==-1)
printf("Stack is empty\n");
else
printf("Peek value is: %d \n",item);
break;
case 5:
exit(0);
break;
}
}
}