Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Develop a stack in c with dynamic memory allocation. Use the following structure

ID: 3776766 • Letter: D

Question

Develop a stack in c with dynamic memory allocation. Use the following structure to create a stack:t
typedef struct Element
{
char c;
struct Element *next;
} Element_Type, *Pointer_Type;
You need to develop the following functions:
1) push(): demands two arguemnts of which the first nominates a pointer. For example, push(&x, ‘A’) to push ‘A’ onto stack X. You need to allocate memory for a new element.
2) pop(): pops and returns the element on the top of the stack and frees the memory space which was occupied by the element.
3) peep(): simply returns the character value of the top element of the stack. No pointers are disturbed.
4) displayAll(): prints all character values of all elements of the stack from top to bottom.

void push(Pointer_Type *q, char ch){……}
char pop(Pointer_Type *q){……}
char peep(Pointer_Type *q){……}
void displayAll(Pointer_Type *q){……}
Test your stack and all functions with at least 10 elements.

Explanation / Answer

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>

struct Element
{
char c;
struct Element *next;
};
struct Element *start=NULL;

void push()
{
   char ele;
struct Element *new_ele,*temp;
int i=0;
for(temp=start;temp!=NULL;temp=temp->next)
{
i++;
}
if(i==10)
{
printf("Stack Overflow");
getch();
}
else
{
new_ele=(struct Element *)malloc(sizeof(struct Element));
printf("Enter value for Element: ");
scanf("%c",&new_ele->c);
new_ele->next=start;
start=new_ele;
}

}

void pop()
{
struct Element *temp,*temp2;
int i=0;
for(temp=start;temp!=NULL;temp=temp->next)
{
i++;
}
if(i==0)
{
printf("Underflow");
getch();
}
else
{
temp2=start->next;
start=temp2;
printf(" ***The value has been poped*** ");
}
}

void display()
{
struct Element *temp;
printf(" ****Stack Values**** ");
for(temp=start;temp!=NULL;temp=temp->next)
{
printf("%c ",temp->c);
}
getch();
}

void peep()
{
struct Element *temp;
int pos,i=0,j=0;
printf("Please enter the position number: ");
scanf("%d",&pos);
for(temp=start;temp!=NULL;temp=temp->next)
{
i++;
}
if(pos>i)
{
printf(" Over Limit ");
getch();
}
else
{
temp=start;
for(j=0;j<pos-1;j++)
{
temp=temp->next;
}
printf(" The value of position %d is :%c",pos,temp->c);
getch();
}
}


int main()
{
int ch;
  
while(ch!=6)
{
  
printf(" 1.Push ");
printf("2.Pop ");
printf("3.Peep ");
printf("4.Display ");
printf("5.exit ");
printf("Enter your choice:");
scanf("%d",&ch);
switch(ch)
{
case 1: push();
break;
case 2: pop();
break;
case 3: peep();
break;
case 4: display();
break;
case 5: exit(0);
}
  
   }
   return 0;
}