TheAlgorithms-C/data_structures/stack/main.c

118 lines
2.0 KiB
C
Raw Permalink Normal View History

// program for stack using array
2019-02-14 22:51:36 +08:00
#include <stdio.h>
2018-02-11 04:00:19 +08:00
void push();
void pop();
2019-02-14 22:51:36 +08:00
void peek();
2018-02-11 04:00:19 +08:00
void update();
void display();
2019-02-14 22:51:36 +08:00
int a[100], top = -1;
int main()
{
2018-02-11 04:00:19 +08:00
int x;
2019-02-14 22:51:36 +08:00
while (1)
2018-02-11 04:00:19 +08:00
{
printf("\n0 or CTRL-C to Exit ");
printf("\n1. Push");
printf("\n2. Pop");
printf("\n3. Peek");
printf("\n4. Update");
printf("\n5. Display");
printf("\nEnter your choice? \n");
2019-02-14 22:51:36 +08:00
scanf("%d", &x);
switch (x)
2018-02-11 04:00:19 +08:00
{
2019-02-14 22:51:36 +08:00
case 0:
return 0;
2018-02-11 04:00:19 +08:00
case 1:
push();
break;
case 2:
pop();
break;
case 3:
2019-02-14 22:51:36 +08:00
peek();
2018-02-11 04:00:19 +08:00
break;
case 4:
update();
break;
case 5:
display();
break;
2018-02-11 04:00:19 +08:00
default:
printf("\nInvalid choice,\nPlease try again.\n");
2018-02-11 04:00:19 +08:00
}
}
2019-02-14 22:51:36 +08:00
return (0);
}
// function for pushing the element
2019-02-14 22:51:36 +08:00
void push()
{
int n = 0;
printf("\nEnter the value to be inserted: ");
2019-02-14 22:51:36 +08:00
scanf("%d", &n);
top += 1;
a[top] = n;
2018-02-11 04:00:19 +08:00
}
// function for poping the element out
2019-02-14 22:51:36 +08:00
void pop()
{
if (top == -1)
{
printf("\nStack is empty");
2019-02-14 22:51:36 +08:00
}
else
{
int item;
item = a[top];
top -= 1;
printf("\nPoped item is %d ", item);
2019-02-14 22:51:36 +08:00
}
}
// function for peeping the element from top of the stack
2019-02-14 22:51:36 +08:00
void peek()
{
if (top >= 0)
printf("\nThe top element is %d", a[top]);
2019-02-14 22:51:36 +08:00
else
printf("\nStack is empty");
2019-02-14 22:51:36 +08:00
}
// function to update the element of stack
2019-02-14 22:51:36 +08:00
void update()
{
int i, n;
printf("\nEnter the position to update? ");
2019-02-14 22:51:36 +08:00
scanf("%d", &i);
printf("\nEnter the item to insert? ");
2019-02-14 22:51:36 +08:00
scanf("%d", &n);
if (top - i + 1 < 0)
{
printf("\nUnderflow condition ");
2019-02-14 22:51:36 +08:00
}
else
{
a[top - i + 1] = n;
}
}
// function to view entire stack
void display()
{
if (top == -1)
{
printf("\nStack is empty");
}
else
{
for (int i = top; i >= 0; i--)
{
printf("%d\n", a[i]);
}
}
}