-1

It should remove all occurrences of a value from the Stack. This is my code but it somehow has a problem with my while statement.

At some test cases, it highlights the while statement and throw me an unhandled exception "System.NullReferenceException"

public bool RemoveAll(T value)
{
    if (Count == 0)
        return false;

    if (Count == 1)
    {
        if (mTop.Data.Equals(value))
        {
            mTop = mTop.Next;
            return true;
        }
    }

    else
    {
        OurListNode<T> pTmp = mTop;
        while (pTmp.Next != null)
        {
            if (pTmp.Next.Data.Equals(value))
            {
                pTmp.Next = pTmp.Next.Next;
            }
            pTmp = pTmp.Next;
        }
        return true;
    }
    return false;
}
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
mrchooo
  • 75
  • 7
  • at some test cases, it highlights the while statement and give me a "System.NullReferenceException" – mrchooo Sep 18 '16 at 05:55

1 Answers1

1

In the line pTmp.Next = pTmp.Next.Next; the assigned value of pTmp.Next.Next might be null, so in while (pTmp.Next != null) pTmp is null and doesn't have Next. Check it for null as well

while (pTmp != null && pTmp.Next != null)
Guy
  • 46,488
  • 10
  • 44
  • 88
  • OMG THANK YOU!! I tried it and it wont throw an error anymore.. but it stills doesn't work the same way I wanted it to because the output of my test code is: 2:1:3:2:3:2:1:2 RemoveAll #1 2:3:2:3:2:2 RemoveAll #3 2:2:2:2 RemoveAll #2 2:2 – mrchooo Sep 19 '16 at 00:35
  • @Angela You are missing the first and last items, instead of `pTmp.Next` use just `pTmp` in the `else` block. – Guy Sep 20 '16 at 04:46