Advertisement
Guest User

Untitled

a guest
Feb 20th, 2019
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.32 KB | None | 0 0
  1. // Finds the minimum, extracts it from the stack and returns it.
  2.         public static int ExtractMin(Stack<int> s)
  3.         {
  4.             int min = FindMin(s);
  5.             Extract<int>(s, min);
  6.             return min;
  7.         }
  8.         // Extracts the first appearance of a value from a stack.
  9.         public static void Extract<T>(Stack<T> s, T toExtract)
  10.         {
  11.             if(!s.IsEmpty())    // if empty nothing to extract
  12.             {
  13.                 T val = s.Pop();
  14.                 if (val.Equals(toExtract))
  15.                     return;     // dont re-insert if this is the wanted value
  16.                 Extract<T>(s, toExtract);   // check in rest of the stack
  17.                 s.Push(val);    // re-insert to keep stack
  18.             }
  19.         }
  20.         // Finds and returns the minimum value in stack, without changing the stack.
  21.         public static int FindMin(Stack<int> s)
  22.         {
  23.             int value = s.Pop();
  24.             if (s.IsEmpty())    // if only value in stack
  25.             {
  26.                 s.Push(value);
  27.                 return value;   // return it
  28.             }
  29.             int min = FindMin(s);   // find the minimum in rest of stack
  30.             if (min > value)
  31.                 min = value;
  32.             s.Push(value);  // re-insert to keep the stack
  33.             return min;
  34.         }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement