Reputation: 35
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
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
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
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