Repository navigation
Expand file tree
/
Copy pathstack_array.c
More file actions
92 lines (81 loc) · 2.13 KB
/
Copy pathstack_array.c
File metadata and controls
92 lines (81 loc) · 2.13 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
/* The following code implements a basic stack with push and pop operations. */
#include<stdio.h>
#define MAXSTACK 4
#define TRUE 1
#define FALSE 0
struct stack
{
int items[MAXSTACK];
int top;
};
int empty(struct stack*); // function prototype for empty; returns TRUE if the stack is empty, FALSE otherwise
void initStack(struct stack*); // function prototype for initStack; initializes the stack to empty state
void push(struct stack*, int); // function prototype for push
void pop(struct stack*); // function prototype for pop
int main(void)
{
struct stack s; // declares a struct variable
int choice = 0, x = 0;
initStack(&s);
printf("This program implements a stack with the following basic operations.\n");
do
{
printf("\n----------- MENU -------------\n");
printf("\n 1. PUSH 2. POP 3. EXIT\n");
printf("\n------------------------------\n");
printf("\nPlease enter your choice (1 / 2 / 3): ");
scanf("%d",&choice);
switch(choice)
{ case 1: printf("\nPlease enter the element to push: ");
scanf("%d",&x);
push(&s, x);
break;
case 2: pop(&s);
break;
case 3: break;
default: printf("\nInvalid choice. Try again.\n");
}
}while(choice != 3);
printf("Thank you.\n")
return 0;
}// end of main
int empty(struct stack *ps)
{
if(ps->top == -1)
return TRUE;
else
return FALSE;
}
void initStack(struct stack *ps)/* DoIt: function definition for initStack */
{
ps->top = -1;
}
void push(struct stack *ps, int x)/* DoIt: function definition for push */
{
if(ps->top == MAXSTACK - 1)
{
printf("\nStack Overflow! Cannot push into a full stack.\n");
return;
}
else
{
ps->top = ps->top + 1;
ps->items[ps->top] = x;
}
printf("\nElement has been pushed successfully.\n");
}
void pop(struct stack *ps) /* DoIt: function definition for pop */
{
int pop = 0;
if(empty(ps))
{
printf("\nStack Underflow! Cannot pop from an empty stack.\n");
return;
}
else
{
pop = ps->items[ps->top];
ps->top = ps->top - 1;
}
printf("\nPopped element is %d.\n", pop);
}