Stack implementation in C

Publié le: 15 juillet 2024
sur la chaîne: Coding with Yogish
15
0

This video contains the implementation of push, pop & peek operations of stacks in C with proper explanation of the code.

For C code of this program, please refer below -
#include stdio.h /* need to add brackets */
#include stdlib.h
#define MAX 100

typedef enum Boolean { False, True }Boolean;

typedef struct Stack
{
int Top;
int S[MAX];
}Stack;

void Push(Stack *, int), Display(Stack *);
int Pop(Stack *), Peek(Stack *);
Boolean IsEmpty(Stack *), IsFull(Stack *);

void main()
{
int x, Item;
Stack St;

St.Top = -1; /* Initializing top */

while(1) /* Infinite loop */
{
printf("Enter choice \n");
printf("1. Push\n");
printf("2. Pop\n");
printf("3. Peek\n");
printf("4. Display\n");
printf("5. Exit\n");
scanf("%d", &x);
switch(x)
{
case 1:
if(IsFull(&St))
{
printf("Overflow\n");
break;
}
printf("Input the element\n");
scanf("%d", &Item);

Push(&St, Item);
break;
case 2:
if(IsEmpty(&St))
{
printf("Underflow\n");
break;
}

Item=Pop(&St);

printf("Popped element: %d\n", Item);
break;
case 3:
if(IsEmpty(&St))
{
printf("Stack is empty\n");
break;
}

Item=Peek(&St);

printf("Top element: %d\n", Item);
break;
case 4:
if(IsEmpty(&St))
{
printf("Stack is empty\n");
break;
}

Display(&St);
break;
/* Display the Stack */
case 5:
exit(0);
/* Exit from the program */

} /* end switch */

} /* end while */

} /* end main */

Boolean IsFull(Stack *St)
{
if((*St).Top==MAX-1)
return True;
else
return False;

} /* end IsFull */

Boolean IsEmpty(Stack *St)
{
if((*St).Top == -1)
return True; /* No element in Stack */
else
return False;

} /* end IsFull */

void Push(Stack *St, int Item)
{
(*St).S[++(*St).Top]=Item; /* Push the element in array 's' */

} /* end Push */

int Pop(Stack *St)
{
int Item;

Item=(*St).S[(*St).Top--]; /* Pop the top element of array 's' */

return Item;

} /* end Pop */

int Peek(Stack * St)
{
int Item;

Item=(*St).S[(*St).Top]; /* Assign top element of the stack to Item */

return Item;
}

void Display(Stack *St)
{
int I;

for(I=(*St).Top;I ge 0;I--) /* Replace ge sign */
printf(" %d\n", (*St).S[I]);

} /* end Display */


Sur cette page du site, vous pouvez voir la vidéo en ligne Stack implementation in C durée heure minute seconde en bonne qualité , qui a été Téléchargé par l'utilisateur Coding with Yogish 15 juillet 2024, Partagez le lien avec vos amis et connaissances, sur youtube cette vidéo a déjà été regardée 15 fois et il a aimé 0 téléspectateurs. Bon visionnage!