Write a C function named findMinimum() that returns the minimum value present at the stack
at O(1) time complexity along with PUSH and POP and Display function. The stack must be
implemented using singly Linked List. (Hints. Apart from TOS pointer take another pointer MIN,
make it always point to the minimum value present at the stack, whenever the findMinimum() is
called return the value pointed by MIN pointer).

Check this out :

``````    Push()
{
// Insert Node as Normal way
if (findMinimum(Stk) != NULL && findMinimum(Stk)->Key > newNode) Min = newNode;
}

Pop()
{

if (findMinimum(Stk) == tos) Min = findNewMinimum(tos);
ros = tos->next;
}

findNewMinimum(Node * T)
{
if (T == NULL) return NULL;
else Min = T
while (T != NULL) { T = T->next; if (T->key < Min->Key) Min = T; }
}
``````

When Pushing an Element, if that element is smaller than the smallest elemnt, Min is updated. Similarly, when Popping, if Top Element is the Minimum element, new smallest element is found.

Hope it helps

Cheers

Alternatively, you can store/push the elements alongwith the current minimum element present in the stack.

For example:

Push Operation:

``````Initialize min = INFINITY;
If element to be pushed < min then
min = element to be pushed;
Push(element, min);
Otherwise Push(element, min);
``````

Now, say the elements 3, 6, 2, 7 were pushed in an empty stack.
So 3 will be pushed with the current minimum that is 3 only.
6 will be pushed with min=3. Then 2 < 3 so 2 will be pushed with min=2. Then 7 will be pushed with min=2.

So now you pop or do whatever the min with which an element was pushed will stay the minimum when you will reach that element after popping out elements one by one.

Example: pop() => 7 with min = 2.
pop() => 2 with minimum 2.
pop() => 6 with minimum 3.
pop() => 3 with minimum 3.

//