ahmed shah
ahmed shah

Reputation: 35

how to replace a value in stack without losing other values?

Suppose I have added 5 values in stack in the stack

student1.grades.Push(60);
student1.grades.Push(70);
student1.grades.Push(80);
student1.grades.Push(90);
student1.grades.Push(100);

I want to replace third value in stack without losing the above two values. tried if condition to find the value in stack but didn't find any method in stack to replace it.

if (student1.grades.Contains(80)==true)
{
     // Unsure what to do here.
}

Upvotes: 1

Views: 2305

Answers (2)

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391396

In order to replace a single value in a stack data structure you can use this algorithm:

Input is the original stack, let's call this STACK

  1. Prepare a temporary stack, that starts empty, let's call this TEMP
  2. Can we pop a single value from the STACK?
    1. If no, then go to step 5
  3. Pop a single value from the STACK
  4. Is it the value we want to replace?
    1. If it is, push back the value we want to replace with onto STACK and go to step 5
    2. If not, push it onto TEMP and go back to step 2
  5. Push all values from TEMP back onto STACK

This will do what I said in the comment to your question: Pop all values above the value you want to replace, pop the value, push back the new value, push back all the values you popped earlier.

Here's a C# extension method for Stack<T> which will accomplish what you want:

public static class StackExtensions
{
    public static void Replace<T>(this Stack<T> stack, T valueToReplace, T valueToReplaceWith, IEqualityComparer<T> comparer = null)
    {
        comparer = comparer ?? EqualityComparer<T>.Default;

        var temp = new Stack<T>();
        while (stack.Count > 0)
        {
            var value = stack.Pop();
            if (comparer.Equals(value, valueToReplace))
            {
                stack.Push(valueToReplaceWith);
                break;
            }
            temp.Push(value);
        }

        while (temp.Count > 0)
            stack.Push(temp.Pop());
    }
}

You would call it like this:

student1.grades.Replace(80, 85);

Upvotes: 2

Milney
Milney

Reputation: 6417

Looks like you don't want to use a stack and instead want to use a List or maybe a Dictionary...

For example, what if there were two marks of 80? How would you know which one to remove??

You may want to have;

Dictionary<String, int> MarksBySubject

Then you can do like;

MarksBySubject.Add("Maths", 80);

and remove it like;

MarksBySubjects.Remove("Maths");

Upvotes: 0

Related Questions