DSU Micro Project
DSU Micro Project
DSU Micro Project
#define MAXSIZE 7
#define TRUE 1
#define FALSE 0
struct Stack
{
int top;
int array[MAXSIZE];
} st;
void initialize()
{
st.top = -1;
}
int isFull()
{
if(st.top >= MAXSIZE-1)
return TRUE;
else
return FALSE;
}
int isEmpty()
{
if(st.top == -1)
return TRUE;
else
return FALSE;
}
int pop()
{
if (isEmpty())
printf("Stack is Empty...\n");
else
{
st.top = st.top - 1;
return st.array[st.top+1];
}
}
void printStack()
{
if(!isEmpty())
{
int temp = pop();
printStack();
printf(" %d ", temp);
push( temp);
}
}
void insertAtBottom(int item)
{
if (isEmpty())
{
push(item);
}
else
{
int top = pop();
insertAtBottom(item);
push(top);
}
}
void reverse()
{
if (!isEmpty())
{
int top = pop();
reverse();
insertAtBottom(top);
}
}
int getSize()
{
return st.top+1;
}
int main()
{
initialize(st);
push(1);
push(2);
push(3);
push(4);
push(5);
printf("Original Stack\n");
printStack();
reverse();
printf("\nReversed Stack\n");
printStack();
return 0;
}
Operations Done:
Input Stack
2 <--- Top
4
8
9
Output Stack
9 <--- Top
8
4
2
Here we are going to use recursion to reverse the stack elements. We will store the top elements
of stack on function stack one by one until stack becomes empty. When stack becomes empty,
we will insert an element at the bottom of stack and then insert all the elements stores in function
stack back in same sequence. Here we will use two user defined functions "insertAtBottom" and
"reverse".
void insertAtBottom(int num) : This function inserts a number "num" at the bottom of stack
using recursion.
void reverse() : This function pop's top element and store it in function stack. Then it recursively
calls itself to reverse remaining stack. Once remaining stack elements are reversed, it calls
insertAtBottom function to insert top element at the bottom of stack.