Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Finds the minimum, extracts it from the stack and returns it.
- public static int ExtractMin(Stack<int> s)
- {
- int min = FindMin(s);
- Extract<int>(s, min);
- return min;
- }
- // Extracts the first appearance of a value from a stack.
- public static void Extract<T>(Stack<T> s, T toExtract)
- {
- if(!s.IsEmpty()) // if empty nothing to extract
- {
- T val = s.Pop();
- if (val.Equals(toExtract))
- return; // dont re-insert if this is the wanted value
- Extract<T>(s, toExtract); // check in rest of the stack
- s.Push(val); // re-insert to keep stack
- }
- }
- // Finds and returns the minimum value in stack, without changing the stack.
- public static int FindMin(Stack<int> s)
- {
- int value = s.Pop();
- if (s.IsEmpty()) // if only value in stack
- {
- s.Push(value);
- return value; // return it
- }
- int min = FindMin(s); // find the minimum in rest of stack
- if (min > value)
- min = value;
- s.Push(value); // re-insert to keep the stack
- return min;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement