Assignment 2 Programming Exercise Stack In the stack example
Solution
#include<stdio.h>
#include<process.h>
#include<stdlib.h>
//To count number of items in the stack
int count = 0;
//Declaration of stack
struct mystack
{
char data; //To store data
struct mystack *next; //Self referencial pointer
}*top = NULL;
typedef struct mystack st;
//Push a data
void push(char ch)
{
st *p;
//Dynamically allocates memory
p = (st *) malloc(sizeof(st));
p -> data = ch;
p -> next = top;
top = p;
count++; //Counter increased
printf(\"\ %c is added to the top of the stack \", p -> data);
}
//Pops an data
int pop( )
{
st *p; p = top;
//Checks underflow condition
if(top == NULL)
printf(\"\ Stack Underflow\");
else
{
top = top -> next;
count--;
return (p -> data);
}
}
//Display the stack data
void displayStack()
{
st *p; p = top;
printf(\"\ Display Stack\");
//Loops till end of stack
while(p != NULL)
{
printf(\"\ Data = %c\", p -> data);
p = p -> next;
}
printf(\"\ ----------------------------\");
}
//Search for an item in the stack
void search(char item)
{
//Dynamically allocates memory to temp to store removed items
char *temp = (char *) malloc(count * sizeof(char));
//To keep track how many items removed from the stack
int i = 0, j;
st *p; p = top;
printf(\"\ ********* Begin to search for %c ********** \ \", item);
//Loops till end of the stack
//Search for the item if found come out of the loop
//If not found add it to the temporary array and delete it from the stack
while(p != NULL)
{
if(p -> data == item)
{
printf(\"\ %c is now found at the top of the stack. \ \", item);
break;
}
else
{
printf(\"\ %c is not at the top of the stack. \ \", item);
*(temp + i) = pop();
p = p -> next;
i++;
}
displayStack();
}
//Adds the removed data back to the stack
for(j = i - 1; j >= 0; j--)
{
printf(\"\ %c needs to be added back to the stack.\", temp[j]);
push(temp[j]);
}
displayStack();
}
void main( )
{
int choice, item;
push(\'H\');
push(\'A\');
push(\'T\');
displayStack();
search(\'H\');
}
Output:
H is added to the top of the stack
A is added to the top of the stack
T is added to the top of the stack
Display Stack
Data = T
Data = A
Data = H
----------------------------
********* Begin to search for H **********
H is not at the top of the stack.
Display Stack
Data = A
Data = H
----------------------------
H is not at the top of the stack.
Display Stack
Data = H
----------------------------
H is now found at the top of the stack.
A needs to be added back to the stack.
A is added to the top of the stack
T needs to be added back to the stack.
T is added to the top of the stack
Display Stack
Data = T
Data = A
Data = H
----------------------------


