Stephanie Stephanie - 2 months ago 6
C# Question

Why does my bool RemoveAll method only return false?

I have to create a RemoveAll method for a stack that takes out all of a particular value and then returns the other values back to the original stack. The method I wrote, however, just returns false. What is the error in my code?

Here's the method I wrote:

public bool RemoveAll(T item)
{
Stack<T> OurStack = new Stack<T>();
Stack<T> tempStack = new Stack<T>();
bool itemRemove = false;
OurListNode<T> pTmp = mTop;

while (OurStack.Count > 0)
{
if (pTmp.Data.Equals(item))
{
itemRemove = true;
pTmp = pTmp.Next;
}
else
{
tempStack.Push(pTmp.Data);
}
}
while (tempStack.Count > 0)
{
pTmp = pTmp.Next;
OurStack.Push(pTmp.Data);
}
return itemRemove;
}


Here's the main I wrote to test the method:

static void Main()
{
OurStack<int> nums = new OurStack<int>();
nums.Push(1);
nums.Push(31);
nums.Push(22);
nums.Push(3);
//nums.RemoveAll(31);

Console.Write(nums.RemoveAll(1));
Console.ReadKey();

Answer

The problem is that:

(OurStack.Count > 0)

and

(tempStack.Count > 0)

Will always be false as when function starts you initialize OurStack and tempStack with new object so it will always be empty(unless you are adding something in Stack constructor code):

Stack<T> OurStack = new Stack<T>();
Stack<T> tempStack = new Stack<T>();

So those list will always be empty ...

Comments