I'm working on a project in C#, for which one of the questions is to make a program that receives a Stack and returns a new Stack with the digits that appear in that stack (every digit that appears will be in the new stack only once).
I made this code, which works pretty fine, but in the middle it just stops working and it gives this error "Unhandled Exception: OutOfMemoryException".
I was wondering what was the problem? From what I can understand it occurs because my program requires more memory than my computer can provide. Correct me if I'm wrong.
Does anyone know what I can do to fix this or how I can improve my code to prevent this?
What can I do in general in codes to prevent this problem from occurring in the future?
Thank you very much in advance. :)
public static Stack<int> Stk(Stack<int> S)
{
int Num;
Stack<int> New = new Stack<int>();
while (!S.IsEmpty())
{
Num = S.Pop();
while (Num != 0)
{
if (!Check(New, (Num % 10)))
{
New.Push(Num % 10);
}
Console.WriteLine("Original Stack: " + New);
Num = Num / 10;
}
}
return New;
}
public static bool Check(Stack<int> S, int num)
{
Stack<int> Temp = new Stack<int>();
while (!S.IsEmpty())
{
Console.WriteLine("Stack Temp: " + Temp);
if (num == S.Top())
{
while (!Temp.IsEmpty())
{
S.Push(Temp.Top());
}
Console.WriteLine("Number found in Stack S!");
Console.WriteLine("Stack S: " + S);
return true;
}
Temp.Push(S.Pop());
}
while (!Temp.IsEmpty())
{
S.Push(Temp.Pop());
}
Console.WriteLine("Stack S: " + S);
Console.WriteLine("Number NOT found in Stack S!");
return false;
}
if (num == S.Top())
{
while (!Temp.IsEmpty()) // Infinite loop, Temp is never empty
{
S.Push(Temp.Top()); // Because of infinite loop, S is just going to fill up memory
}
//...
I'm not familiar with Top()
on a Stack<T>
but judging from the rest of the code it looks like it doesn't remove an object from your stack (the function I know of that does this is Peek
). If that's the case you've got an infinite loop that fills up all available memory and ultimately runs out.
Edit: This answer focuses on the problem you're having. This smells like homework to me so I'm not going to rewrite it but I'd suggest paying at @ckuri's comment on this answer down below. It looks like you're doing a lot more work than you should. You may want to look at iterating the stack rather than popping to a whole new stack.